3

Obviously all local arrays (not dynamically allocated) are on the stack, but are global ones located on the stack as well?

Other types of global variable are on the heap but I got the hint that arrays are a different story and are allocated at the bottom of the stack. it that true?

Again, I am not talking about dynamically allocated ones which are always on the heap.

tod
  • 1,539
  • 4
  • 17
  • 43
pHbits
  • 376
  • 2
  • 13

2 Answers2

7

No, global data are not allocated on the stack. They are allocated statically and the memory is reserved at compile time.

One simple way to think about this is to consider threads. There is one stack per thread. But global data is shared between threads. So global data cannot be allocated on a stack.

Other types of global variable are on the heap.

Not so. Global data is never allocated on the heap. Heap allocation is performed dynamically at runtime.

Perhaps you have a pointer global variable. And you assign a dynamic array to that pointer. In that scenario the pointer is a global, but the array is a dynamic heap allocated object.

So perhaps you have code like this:

int *arr;
....
arr = calloc(N, sizeof(int));

In that scenario, arr is a global object, but *arr is heap allocated.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
2

Other types of global variable are on the heap - that's not true, they're allocated in the data segment. I believe arrays are also allocated there

Andrey Chernukha
  • 21,488
  • 17
  • 97
  • 161