Memory allocation for array on Stack or Heap (C) [closed]
Asked Answered
E

4

6

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.

Ephemera answered 2/1, 2017 at 7:52 Comment(3)
Please see this discussion on why not to cast the return value of malloc() and family in C..Subnormal
Stored in stack frame of main() which is of 8 MB by defaultDeepsix
There is no stack in the C language.Apologete
B
8

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.

Baggage answered 2/1, 2017 at 7:56 Comment(0)
S
4

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.

Subnormal answered 2/1, 2017 at 7:57 Comment(0)
C
2

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

Crustal answered 2/1, 2017 at 7:55 Comment(0)
M
2

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

Mckamey answered 2/1, 2017 at 8:24 Comment(2)
There's also the minor point VLA's aren't available in standard c++ at all. No need for a style guide to tell you not to use them. And "style" guides outlawing features completely irregardless of all other considerations is asinine.Baggage
Does the Google C++ Style Guide apply to C code - like OP's?Fourlegged

© 2022 - 2024 — McMap. All rights reserved.