c程序中的分段错误

cod*_*rix 6 c gcc segmentation-fault

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

#include<stdio.h>

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

但当我在ubuntu 10.04下运行我的"gcc"编译器时,我得到了:

Segmentation fault
Run Code Online (Sandbox Code Playgroud)

所以任何人都可以解释为什么会这样.

#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;
}
Run Code Online (Sandbox Code Playgroud)

这也导致分段错误在此先感谢

Pra*_*rav 5

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

修饰字符串文字的内容(即代码中的"Hello World")是未定义的行为.

ISO C99(第6.4.5/6节)

如果这些数组的元素具有适当的值,则不确定这些数组是否是不同的.如果程序试图修改这样的数组,则行为未定义.

尝试使用字符数组.

char p[] = "Hello World";
p[1] = 'l'; 
Run Code Online (Sandbox Code Playgroud)

编辑

你修改过的代码

#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;
}
Run Code Online (Sandbox Code Playgroud)

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