开发者

memory allocation for local static and local variable

开发者 https://www.devze.com 2023-03-01 10:21 出处:网络
1. void main(void) { int *ptr1; ptr1 = (int *)malloc(..); } 2. void main(void) { static int *ptr2; ptr2 = (int *)malloc(..);

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 pt开发者_开发技巧r1 & ptr2?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消