Dynamic memory allocation is done in heap memory.
The one you showed is done dynamically but in stack.
Trying to keep it less complex, let's try to understand this.
You may have studied stack data structure in your classes. That's what is used for allocation in case of this:
int a[n];
Stack size obviously has a limit. Like if 100
was the maxsize, allocating beyond it would cause a stack overflow.
The issue is that there is no way to handle such a stack overflow at runtime.
Let's say n
was 10000
and suppose there was't enough memory. It would just cause a trap.
If you want, you can see it live by allocating memory for a large number, like 100000000ULL
. It will just crash.
To allocate in stack, you can also use alloca(3)
. If you read it's description, it says:
If the allocation causes stack overflow, program
behavior is undefined.
So basically no way to have an ensured check. Generally if it fails program terminates unless you have a unique OS that gives you the capability to handle it.
Variable length arrays(int a[n]
) and alloca(3)
allocate in stack.
malloc(2)
allocates in heap.
On return, as per the man page,
On error,
these functions return NULL.
So you can make a runtime check:
int *a = malloc(1234);
if (a == NULL) {
fprintf(stderr, "malloc(2) failed!\n");
// handle it
}