Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check array created successfully in C

Tags:

arrays

c

memory

In C there are 2 ways to create arrays:

int array[100]; 

and

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

With the second statement its easy to check if there was enough memory available to create the array for example:

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

But how would you check that the first worked successfully? Assuming this was running on a microcontroller and not a computer.

like image 309
Dean Avatar asked Apr 24 '14 22:04

Dean


2 Answers

There is no such thing as a recoverable failure from allocation of an array on the stack (the first way). It will only fail if allocating it causes a stack overflow, at which point your program has aborted/terminated anyway.

When you allocate the array the first way, it is being allocated on the stack, usually at function call time. If there isn't enough room on the stack to allocate it, the program aborts with a stack overflow/segfault error.

When you allocate the second way, you are asking the memory manager for memory on the heap at the time you actually call malloc.

EDIT: As mentioned by @Deduplicator, if you're on a system without memory protection, not having enough free stack space to allocate an array can leave to overruns and much subtler problems (although most likely it will fail on an illegal instruction soon enough).

like image 183
Linuxios Avatar answered Nov 18 '22 21:11

Linuxios


The first piece of code stores the array in the stack The second stores the array in the heap

Stack memory is pre-allocated thorughout the thread, having said that, unless u'r allocating huge amounts of data on the stack, you shouldn't be generally worried about stack space.

Checking available stack size in C

Edit: In that case you ought to make sure, in-advance that you have enough stack (defined in your IDE/Compiler/Linker/Proprietary software) for the depthest of the calls throughout your code execution. This can be known in advance in compile-time, no need for runtime checks.

like image 33
HLL Avatar answered Nov 18 '22 23:11

HLL