Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this array different from dynamically allocated array

Tags:

arrays

c

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?

like image 402
Jersey Devil Avatar asked Dec 08 '25 01:12

Jersey Devil


2 Answers

There are two main points:

  1. malloc will usually align memory to sizeof(max_align_t) bytes while allocation on the stack won't.

  2. Allocation on the stack can cause stack overflow while allocation with malloc should return an error upon memory overuse.

  3. You are allowed to return a pointer returned by malloc but not a pointer from an allocation on the stack.

like image 153
S.S. Anne Avatar answered Dec 10 '25 13:12

S.S. Anne


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.

like image 34
dbush Avatar answered Dec 10 '25 14:12

dbush