Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory allocation for local static and local variable

Tags:

c

unix

1.

void main(void)
{
  int *ptr1;
  ptr1 = (int *)malloc(..);
}

2.

void main(void)
{
  static int *ptr2;
  ptr2 = (int *)malloc(..);
}

I want to ask how is memory allocation done for ptr1 & ptr2?

like image 747
Aragorn Avatar asked Apr 09 '26 18:04

Aragorn


1 Answers

The ptr1 pointer itself is allocated on the stack. ptr1 points to memory on the heap.

The ptr2 pointer itself is allocated on program startup (before main is invoked) and is global but just happens to be visible only in main because it is declared in its scope. ptr2 points to memory on the heap as well.

Declaring ptr2 outside of main would only make it visible in all functions below it, but its storage will be the same.

like image 53
Blagovest Buyukliev Avatar answered Apr 11 '26 13:04

Blagovest Buyukliev



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!