Let's say I write this snippet:
#include<stdio.h>
int main()
{
int elements;
printf("enter number of elements for array\n");
scanf("%d", &elements);
int arr[elements];
}
And I dynamically allocate memory for an array by malloc, whats the difference besides that malloc allocates memory in heap?. How much memory will be allocated in the first case at compile time?
There are two main points:
malloc will usually align memory to sizeof(max_align_t) bytes while allocation on the stack won't.
Allocation on the stack can cause stack overflow while allocation with malloc should return an error upon memory overuse.
You are allowed to return a pointer returned by malloc but not a pointer from an allocation on the stack.
This is called a variable length array. They reside in the same place as other local variables, typically on the stack, and the space for them is set aside at runtime.
If you were to use sizeof(arr), this would be one of the few instances where a sizeof expression is evaluated at runtime instead of compile time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With