Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is accessing the static value using a global pointer variable is valid?

Can I access the static variable using the global pointer?

//In main.c file
static int c = 20; #Static vairble 
int *ptr = &c; #Global pointer variable
int main(){
  fun();
  printf("%d\n", c);
}

//In sub.c file
extern int *ptr;
void fun(){
  ++*ptr;
}

When I tried to access the *ptr global variable using the extern keyword in another file I'm able to access the static variable c and even the changes made on the *ptr is reflecting on c in main.c file

  1. Why does "ptr" not loses its global property even after its assigned by a static variable address?

  2. Does static and global are stored in two different segments of memory or they both share the same data segment of memory?

  3. Can global variables store non-constant values?

like image 824
BasavarajaMS Avatar asked May 26 '26 03:05

BasavarajaMS


1 Answers

static is not about laying the object into a portion of memory that cannot be altered /addressed from other translation units. It is just about defining that the object has internal linkage and therefore cannot be grabbed by other translation units through this (internal) name.

But if you somehow get the memory address of an object declared static in another translation unit, you may legally access the object.

So your construct is valid.

One might just obey the "static initialization order fiasco" when other translation units draw copies of your ptr (probably before this got pointed to c). Consider, for example, what might happen when another translation unit contains at file scope...

extern int *ptr;
int *myPtr = ptr;
...
int main() {
   int x = *myPtr;
}
like image 62
Stephan Lechner Avatar answered May 28 '26 18:05

Stephan Lechner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!