Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialized vs uninitialized global const variable in c

Tags:

c

Pardon me, I am not very good in explaining questions. So I start with example directly

Look at following example

const int a=10;
int *ptr;

int main(){
    ptr=&a; 
    *ptr=100;   // program crashes
    printf("%d",a);
}

But If I made a slightly change in above code as following

const int a; // uninitialized global variable 

Then the above code works fine.

So my question is why compiler behaves differently for uninitialize and initialize global const variables?

I am using gcc for windows (mingw).

like image 865
A.s. Bhullar Avatar asked Nov 30 '22 01:11

A.s. Bhullar


1 Answers

You are modifying a const object, and that is simply undefined behavior - so don't do it, and don't ignore compiler warnings.

Now, the actual reason for the different behavior in your particular case is that for const int a=10; the value 10 has to be stored somewhere. Since the variable is const, the linker places it in the .rodata or a similar read only section of the executable. When you're trying to write to a read-only location, you'll get a segmentation fault.

For the uninitialized case, const int a , the a needs to be initialized to zero since it's at file scope (or; a is a global variable). The linker then places the variable in the .bss section, together with other data that also is zero initialized at program startup. The .bss section is read/write and you get no segfault when you try to write to it.

All this is not something you can rely on , this could change with minor modification to the code, if you use another compiler or a newer/older version of your compiler etc.

like image 118
nos Avatar answered Dec 05 '22 07:12

nos