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?
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.
*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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With