Reputation: 41
When compiled by gcc and then run, the code
int *p; int main() {*p = 1;}
causes a segmentation fault.
Apparently, the memory location contained in p cannot be written to.
Why????
On the other hand,
int q[]; int main() {*q = 1;}
runs just fine.
What's going on here??
Why does p contain only read-only memory?
Upvotes: 4
Views: 2543
Reputation: 284876
The first example has a wild (not explicitly initialized) pointer. Since it's not an automatic variable, it is set to 0, which clearly is not memory you own. You can see this by printing it out with:
printf("%p\n", p)
As for the second, C99 §6.9.2 actually gives this as an example:
EXAMPLE 2 If at the end of the translation unit containing
int i[];
the array i still has incomplete type, the implicit initializer causes it to have one element, which is set to zero on program startup.
In general, objects with tentative definition (no initializer) are initialized with 0, which for an array means a 1-element array with element value 0.
Upvotes: 10
Reputation: 7951
*p = 1;
causes Segmentation fault because it was not allocated any memory before the assignment.
*q = 1;
works because the compiler (gcc 4.2.1 on Mac OS X) warns that q[] is assumed to have one element.
Upvotes: 3
Reputation: 44314
Your first example causes a segmentation fault because you are dereferencing NULL. You never initialize p
with a value, and because it's a global it will be NULL. Thus, you dereference NULL, and boom.
I'm not sure how the second example is valid - gcc notes that it is assuming q
to be a 1-element array, which is why that won't blow up.
Upvotes: 0