Do global pointers cause a segmentation error?

When compiling gcc and then running it, the code

  int * p;
     int main () {* p = 1;}

causes a segmentation error.

Apparently, the memory location contained in p cannot be written to.

Why????

On the other hand,

  int q [];
     int main () {* q = 1;}

works great.

What's going on here?

Why does p only contain read-only memory?

+4
source share
3 answers

The first example has a wild (not explicitly initialized) pointer. Since this is not an automatic variable, it is set to 0, which is clearly not your property. You can see this by printing it with:

printf("%p\n", p) 

As in the second, C99 Β§6.9.2 actually gives this as an example:

EXAMPLE 2 If at the end a translation unit containing

int i [];

the array I still have an incomplete type, the implicit initializer makes it have one element, which is zero when the program starts.

In the general case, objects with a preliminary definition (without an initializer) are initialized with 0, which for an array means a 1-element array with element value 0.

+10
source

*p = 1; causes a segmentation error because no memory was allocated before the assignment.

*q = 1; works because the compiler (gcc 4.2.1 on Mac OS X) warns that q [] is supposed to have one element.

+3
source

Your first example is causing a segmentation error, since you are looking for NULL. You never initialize p value, but because it is global, it will be NULL. This way you are looking for NULL and the arrow.

I'm not sure how the second example is valid - gcc notes that it accepts q as a 1-element array, so it won't explode.

0
source

Source: https://habr.com/ru/post/1315354/


All Articles