You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

出现Segmentation fault (core dumped)错误,求原因及字符串替换方案

问题分析与解决

错误原因

  • 字符串常量不可修改:你代码里string a = "bob";中的"bob"是字符串常量,它被存储在程序的只读内存区域。当你用string(本质是char*)指向它后,尝试通过a[c] = b[c]修改这个只读区域的内容,直接触发了段错误,因为操作系统不允许修改只读内存。
  • 内存空间不足:退一步说,就算a指向可写内存,"bob"的内存空间只能容纳3个有效字符加结束符'\0',而b指向的"steve'"长度更长,强行逐个赋值会导致内存越界访问,同样会 prob心力 "*//这费�ardo sustained不变,其制.nl相关联的异常。

正确实现方法

方法1:动态分配内存(推荐)

因为cs50的string是char*,可以通过malloc分配足够的内存来存储b的内容,避免只读内存和空间不足的问题:

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    string a = "bob";
    string b = "steve'";
    
    // 分配能容纳b所有字符(包括结束符)的内存
    a = malloc(strlen(b) + 1);
    // 检查内存分配是否成功
    if (a == NULL) {
        return 1;
    }
    
    // 手动逐个字符复制(包括'\0')
    int len_b = strlen(b);
    for (int c = 0; c <= len_b; c++) {
        a[c] = b[c];
    }
    
    printf("%s\n", a);
    // 记得释放动态分配的内存,避免内存泄漏
    free(a);
    return 0;
}

也可以用strcpy替代手动循环,简化代码:

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    string a = "bob";
    string b = "steve'";
    
    a = malloc(strlen(b) + 1);
    if (a == NULL) {
        return 1;
    }
    strcpy(a, b); // 直接复制整个字符串
    
    printf("%s\n", a);
    free(a);
    return 0;
}

方法2:使用固定大小的字符数组

如果你能提前预估字符串的最大长度,可以直接定义一个足够大的可写字符数组,避免动态内存分配:

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    // 定义足够大的栈上字符数组,默认初始化为"bob"
    char a[100] = "bob";
    string b = "steve'";
    
    // 手动复制或用strcpy都可以
    int len_b = strlen(b);
    for (int c = 0; c <= len_b; c++) {
        a[c] = b[c];
    }
    
    printf("%s\n", a);
    return 0;
}

内容的提问来源于stack exchange,提问作者Harr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 08:27:51