Why there is a segmentation fault in this case? [duplicate]
Possible Duplicate:
why segmentation fault in this program
int main()
{
char *a="asdasd";
int i;
for(i=0;i<6;i++)
{
(*a)++;
printf("\n%s",a);
}
}
Output Segmentation fault
int main()
{
char a[]="asdasd";
int i;
for(i=0;i<6;i++)
{
(*a)++;
printf("\n%s",a);
}
}
No segmentation fault
In the first one, you're declaring a pointer to char
and assigning the value of a pointer to a constant char
to in. In the second one, you're declaring an array of char
and giving it it an initial value, but it ends up to not be a constant. In the loop, you try to increment the value at the location of the pointer or the first index of the array. Since the pointer one points to a constant char
, it fails: you can't change a constant. The array, however, can be modified, and therefore, does not fail.
The architecture you're using implements char *a="asdasd";
by storing the constant string "asdasd"
in pages that are marked read-only because it really is const char*
even though you said otherwise. This is a good thing because it makes it easier for your operating system to share these pages across multiple processes (like it can do with code).
If you're using gcc you can use -Wwrite-strings
to have the compiler warn you when you do this, or if you're using an older version (pre-4.0), -fwritable-strings
(or -traditional
) to not use the read-only page mapping.
精彩评论