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
#include
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)