c程序中的分段错误

只是为了测试我创建了以下代码
#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&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...