Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global pointers cause segmentation fault?

Tags:

c

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?

like image 504
ManRow Avatar asked Dec 12 '22 20:12

ManRow


2 Answers

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.

like image 114
Matthew Flaschen Avatar answered Jan 05 '23 18:01

Matthew Flaschen


*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.

like image 40
vpit3833 Avatar answered Jan 05 '23 16:01

vpit3833