Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically allocating array with the [] operator instead of using malloc?

I am sure this has been asked a million times but I couldn't find an answer that explained it. I have been told to never do this but I haven't really understood why. Why doesn't something like this count as dynamically allocating memory and why is it that bad?

int a;
scanf("%d",&a);
int arr[a];
like image 455
spiroulis Avatar asked Apr 16 '21 13:04

spiroulis


People also ask

How do you dynamically allocate an array?

dynamically allocated arrays To dynamically allocate space, use calls to malloc passing in the total number of bytes to allocate (always use the sizeof to get the size of a specific type). A single call to malloc allocates a contiguous chunk of heap space of the passed size.

What can I use instead of malloc?

An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used for storing similar types of elements as the data type must be the same for all elements.

What does malloc () return when dynamically allocating an array?

The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.


1 Answers

This is not dynamic allocation but a variable length array.

The lifetime of such an array is its enclosing scope, just like an array with a fixed size, so you don't need to worry about deallocation. These arrays typically reside on the stack, so the size of the stack does put limitations on how big a VLA (or any array) can be.

If you find that a VLA is too big for the stack, you can always fall back to using malloc.

like image 183
dbush Avatar answered Nov 06 '22 16:11

dbush