Reputation: 85
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?
Upvotes: 3
Views: 100
Reputation: 15576
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.
Upvotes: 3
Reputation: 422
Variable length arrays (VLA) is a feature that is introduced by the C99 standard, and made optional by the C11 standard. The main difference between malloc
allocations and VLA is that, returning the pointer obtained by calling malloc
from a function is normal, but returning a local VLA (or more precisely, returning the pointer which points to the initial element of the array) from a function is almost always wrong. It is undefined behaviour if that pointer is used in the calling function. Compare these two functions:
int *f(int n)
{
int arr[n]; // VLA
/* Do some stuff */
return arr; // WRONG: returns address of local variable
}
int *g(int n)
{
int *arr = malloc(n * sizeof *arr);
if (arr == NULL) {
/* Memory allocation failed. Treat accordingly */
}
/* Do some stuff */
return arr;
}
Another difference is; there's no way to detect errors on large VLA allocations, but it is possible on malloc
allocations by checking the pointer against NULL
.
Upvotes: 0
Reputation: 224112
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.
Upvotes: 2