Check array successfully created in C

In C, there are 2 ways to create arrays:

int array[100]; 

and

 int * array = malloc(sizeof(int)*100); 

With the second statement, it is easy to check if there is enough memory to create an array, for example:

 if(array == NULL){ goto OutOfMemory; } 

But how would you verify that the first worked successfully? Assuming this works on a microcontroller, not a computer.

+6
source share
2 answers

There is no such thing as a recoverable failure while allocating an array on the stack (first method). It will fail if the allocation leads to a stack overflow, after which your program is interrupted / terminated anyway.

When you allocate an array in the first way, it is allocated on the stack, usually when a function is called. If there is not enough space on the stack to allocate it, the program aborts with the / segfault error.

When you allocate the second method, you request a memory manager for memory on the heap during a malloc call.

EDIT: As @Deduplicator mentioned, if you are on a system without memory protection and you donโ€™t have enough free space on the stack to allocate an array, this can lead to overflows and much more subtle problems (although most likely the instruction will be soon enough).

+10
source

The first part of the code stores the array on stack second stores the array in heap

The stack memory is pre-allocated to the stream, saying this, if you do not allocate a huge amount of data on the stack, you should not worry at all about the stack space.

Checking available stack size in C

Edit: In this case, you should make sure that you have enough stack (defined in your IDE / compiler / linker / proprietary software) for the most delicate calls during code execution. This may be known in advance at compile time; there is no need to check the runtime.

+1
source

All Articles