Memory allocation for array on Stack or Heap (C)

Aditya Naidu picture Aditya Naidu · Jan 2, 2017 · Viewed 13.4k times · Source

Consider the following C code:

    #include <stdio.h>
    #include <stdlib.h>

    int main() {

        int arrSize;
        scanf("%d", &arrSize);
        printf("%d\n",arrSize);

        int *dynArr = (int *)malloc(sizeof(int)*arrSize);
        int arr1[arrSize];

        return 0;
    }

In the code above, arrSize is size of an array taken from the user input. I want to know if the following observations are correct:

  • dynArr is a dynamic array which is allocated in the memory during runtime on heap. Size of dynArr can be modified using realloc function.

  • arr1 is also allocated in the memory during runtime but is not dynamic (i.e. their size cannot be modified) and it is allocated on Stack.

Answer

i) dynArr is a dynamic array which is allocated memory during runtime from heap section. Size of dynArr can be modified using realloc function.

Yes, if realloc can find a big enough block. Although technically, the pointer isn't an array. It points to the first element of an array.

ii). arr1 is also allocated memory during runtime but is not dynamic i.e. their size cannot be modified. Memory is allocated from the stack or data section. (Not sure from which section heap or stack/data the memory is allocated and why).

The size of the array is dynamic, it's lifetime isn't. It will be reclaimed automatically the moment main returns. Variable length arrays are usually allocated on the call stack. And yes, you cannot change it's size once you declared it.


If you are now wondering when to use one over the other there are a few points to consider:

  1. The memory reserved for the call stack is limited (more so than the heap by far). It's easy to overflow if you declare a huge VLA on it.

  2. The memory returned from malloc and its kin can outlive the stack frame where it was allocated.

  3. Generally, allocating VLA's can be faster than allocating memory with malloc. One is a simple progression of the stack frame pointer, while the other involves the heap's memory allocator and its logic.