问题
#include <stdio.h>
#include <conio.h>
void test(char *p)
{
p = p + 1;
*p = 'a';
}
int main()
{
char *str = "Hello";
test(str);
printf("%s", str);
getch();
return 0;
}
When I run this code it gives segmentation error ? why is this happening. The const theory is not clear to me... whereas if I declare str as char str[], it does the job. Are they not both basically the same things ?
回答1:
str
is pointing to a string literal, you are attempting to modify the string literal in the function test
on this line:
*p = 'a';
It is undefined behavior to attempt to modify a string literal. You can alternatively, make a copy of the string literal into a array as follows:
char str[] = "Hello";
now it is perfectly ok to modify str
. From the draft C99 standard, under section 6.4.5 String literals
paragraph 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.
回答2:
*p = 'a';
The problem is the above statement tries to modify the read only segment. String literal "Hello"
resides in read only segment and can not be modified.
char str[] = "Hello";
The above statement copies Hello
to str
character array and the array contents can be modified.
来源:https://stackoverflow.com/questions/18215001/char-str-vs-char-str-segmentation-issue