Segmentation fault in c program runtime

来源:互联网 发布:吉祥网络 传奇 编辑:程序博客网 时间:2024/05/18 03:07

There is  a common fault in c when using pointer to represent array or string. For example

#include <stdio.h>
void main(){
char *p="china";
printf("%s",p);
}

This program will get the result 

china

However, when you want to add a line to change the element of the string, like

#include <stdio.h>

void main(){                                  
char *p="china";

        p[1]='x';                           //line 3
printf("%s",p);
}

The program will not have problem to compile. But when running it on gcc or debug it, you will see a segmentation fault  when the program goes to line 3.
I have looked for the reason of this fault for a while. Mostly they will talk about I want to write to the memory which is read only. But no one tell me how to handle this problem.
Yes, I know if I first declare a array and assay the address to the pointer, but the question is If I can "assign" a string to the pointer, why I cannot change the value in the pointer?
Hopefully I can find the solution.