相关疑难解决方法(0)

获取分段错误

我在SO中看到了很多关于在C程序中获取分段错误的问题,我认为在这里引用这些是很好的,这是一些导致分段错误的问题.我的答案发布在下面.

正如在一些答案中所写,对于所有情况,行为都是未定义的,尽管许多人将它们视为 分段错误,因此这个问题是关于导致这种"症状"的原因.

在下面的例子中,当我运行程序时出现分段错误,你能确定原因吗?

1)

char *str = "foo";
str[0] = 'b';   // << Segfault hre
Run Code Online (Sandbox Code Playgroud)

2)

char str[] = "foo";
char *newStr = malloc(strlen(str));
strcpy(newStr, str);
free(newStr);   // << Segfault here
Run Code Online (Sandbox Code Playgroud)

3)

char *str = malloc(4 * sizeof(char));
str = "foo";
free(str);      // << Segfault here
Run Code Online (Sandbox Code Playgroud)

4)

char *str = malloc(4 * sizeof(char));
strcpy(str, "foo");
free(str);
if (str != NULL)
    free(str);      // << Segfault here
Run Code Online (Sandbox Code Playgroud)

5)

char *str = "something and then foo";
printf("%s", str[19]);    // …
Run Code Online (Sandbox Code Playgroud)

c segmentation-fault access-violation

15
推荐指数
2
解决办法
7867
查看次数

标签 统计

access-violation ×1

c ×1

segmentation-fault ×1