Memory allocation for array on Stack or Heap (C)

17.2k views Asked by At

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.

4

There are 4 answers

0
user2736738 On

It allocates memory from free memory store. Now there is nothing called heap and stack in memory in case of C..it is something logically we consider in case of C.(In implementation of C)]


Only thing we are bothered about whether we need something which you want to be alive even if the scope of where it is declared ends or not.

For heap it is the case .. for stack it is not.

In your case

int arr1[arrSize]; is allocated on the same frame on which this main function local variables are stored.

Dynamic allocation

You control the exact size and the lifetime of these memory locations. If you don't free it, you'll run into memory leaks, which may cause your application to crash, since it, at some point cannot allocation more memory. (dynArr)

Actually...

Heap

The heap is a region of your computer's memory that is not managed automatically for you, and is not as tightly managed by the CPU. It is a more free-floating region of memory (and is larger). To allocate memory on the heap, you must use malloc() or calloc(), which are built-in C functions.

Once you have allocated memory on the heap, you are responsible for using free() to deallocate that memory once you don't need it any more. If you fail to do this, your program will have what is known as a memory leak. That is, memory on the heap will still be set aside (and won't be available to other processes).

Stack

It's a special region of your computer's memory that stores temporary variables created by each function (including the main() function). The stack is a "LIFO" (last in, first out) data structure, that is managed and optimized by the CPU quite closely. Every time a function declares a new variable, it is "pushed" onto the stack. Then every time a function exits, all of the variables pushed onto the stack by that function, are freed (that is to say, they are deleted). Once a stack variable is freed, that region of memory becomes available for other stack variables.

Resources

0
StoryTeller - Unslander Monica On

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.

0
Sourav Ghosh On

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

  • No, dynArr is a pointer, which is initialized using the returned pointer by malloc(). Remembers, arrays are not pointers and vice-versa. IN some cases, an array name decays to a pointer to the first element of the array, but that does not make both the same.

  • size of dynArr is the size of the pointer, not the size of the memory location it points to. Using the correct words, in can be represented as, the size of memory it points to can be changed using realloc().

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).

This is called variable length array. Other points are correct.

Quoting C11, chapter ยง6.7.6.2

If the size is an expression that is not an integer constant expression: if it occurs in a declaration at function prototype scope, it is treated as if it were replaced by *; otherwise, each time it is evaluated it shall have a value greater than zero. The size of each instance of a variable length array type does not change during its lifetime.

2
rubyyhj On

Actually, the variable length array are not allowed in Google C++ Style Guide. It has a natural-looking syntax and it's efficient, however, because of they allocate a data-dependent amount of stack space, it can trigger serious and mysterious memory overwriting bugs:

Sometimes "It ran fine on my machine, but dies mysteriously in production".