Why do we need dynamic memory allocation, even though we can use variable-length arrays?

advertisements

Why do we need dynamic memory allocation despite we can use variable-length arrays instead?

We can allocate dynamic memory at run-time with a variable length array as:

unsigned int x;
printf("Enter size:");
scanf("%d",&x);
int arr[x];

Also we can allocate memory at run-time by using one of dynamic memory allocation functions as:

unsigned int x,*p;
printf("Enter size:");
scanf("%d",&x);
p = (unsigned int *)malloc(x);

So, In both case we can allocate memory during run-time.So, Why do we need dynamic memory allocation despite we can use variable-length arrays instead? And what benefits we can get when using one of dynamic memory allocation functions than arrays?

Edit code for passing array:

unsigned int *func(unsigned int *p)
{
   *p=10; // any processing on array

   return p;  // we could return a pointer to an array

}

int main()
{
  unsigned int x,*P;
  printf("Enter size:");
  scanf("%d",&x);
  unsigned int arr[x];

  p = func(arr);
}


Because it has different use cases.

You use automatic memory when you allocate it in a calling routine and you can pass that memory to callees at will. But you will never be able to return it to a caller.

Imagine a library that would use opaque structures to store data - a kind of OOP in C. The API is likely to have routines with this signature:

void * buildEltOfTypeXX(param1, param2, ...);

to create and initialize the opaque structures. In that case, it is evident that the memory must use dynamic allocation (malloc) and not automatic because you would return a dangling pointer. And with that pattern, the caller will get ownership of the memory and will have to free it when it no longer needs it.