c - c程序中的段错误

标签 c gcc segmentation-fault

只是为了测试,我创建了以下代码:

#include<stdio.h>

int main(){
    char *p = "Hello world";
    *(p+1) = 'l';
    printf("%s", p);
    return 0;
}

但是当我在 ubuntu 10.04 下运行我的“gcc”编译器时,我得到:

Segmentation fault

那么谁能解释为什么会这样。

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

int main(){
    char *p = malloc(sizeof(char)*100);
    p = "Hello world";
    *(p+1) = 'l';
    printf("%s", p);
    free(p);
    return 0;
}

这也会导致段错误 提前致谢

最佳答案

char *p = "Hello world"; *(p+1) = 'l';

修改字符串文字(即代码中的“Hello World”)的内容是未定义行为。

ISO C99(第 6.4.5/6 节)

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

尝试使用字符数组。

char p[] = "Hello World";
p[1] = 'l'; 

编辑

你修改后的代码

#include<stdio.h>
#include<stdlib.h>
int main()
{
   char *p = malloc(sizeof(char)*100);
   p = "Hello world"; // p now points to the string literal, access to the dynamically allocated memory is lost.
   *(p+1) = 'l'; // UB as said before edits
   printf("%s", p);
   free(p); //disaster
   return 0;
}

也会调用未定义行为,因为您正在尝试释放尚未使用 malloc 分配的内存部分(使用 free)

关于c - c程序中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4416698/

相关文章:

c++ - 我的 Linux 开发项目的 Clang vs GCC

c - 为数组元素赋值时出现段错误

c - ubuntu 12.04 yylex() 调用中的段错误(核心转储)

c - x64 上是否需要 int ?

通过mmap分配的内存是否可以覆盖数据段

c++ - 直接访问硬盘?

C++11 字符串属性和 gcc 版本

c - 程序运行并显示输出后段错误核心转储

c - 如何在 C 中使用 round() 函数

c - MPLAB无限循环