Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use malloc() when I can just define a variable-length array?

Tags:

arrays

c

I was reading about creating array dynamically in C. So the proper way as described there was:

int n;
scanf("%d", &n);
int *arr = (int*)malloc(n*sizeof(int));

But then I thought if I could just do something like this-

int n, i, sum=0;
scanf("%d", &n);
int arr[n];

And I compiled and ran it without any error. So, my question is why should I use malloc()? Does this have something to do with the old and new C versions?

like image 286
Farhan Fuad Avatar asked Jul 20 '18 18:07

Farhan Fuad


People also ask

Why are variable length arrays bad?

The biggest problem is that one can not even check for failure as they could with the slightly more verbose malloc'd memory. Assumptions in the size of an array could be broken two years after writing perfectly legal C using VLAs, leading to possibly very difficult to find issues in the code.

What is the difference between variable length array and dynamic memory allocation?

Allocation: VLAs are allocated on the stack, whereas dynamic arrays are allocated on the heap. So, VLAs are faster than dynamic memory. Since the compiler has to cleanup memory (for dynamic array) after usage.

Can we define size of array with variable?

Variable length arrays are also known as runtime sized or variable sized arrays. The size of such arrays is defined at run-time. Variably modified types include variable length arrays and pointers to variable length arrays. Variably changed types must be declared at either block scope or function prototype scope.

When should we use malloc ()?

Malloc is used for dynamic memory allocation and is useful when you don't know the amount of memory needed during compile time. Allocating memory allows objects to exist beyond the scope of the current block. C passes by value instead of reference.


2 Answers

There are at least five benefits to using malloc over variable length arrays.

  1. Most notably, objects created with malloc persist after execution of the current block ends. This means that such objects can be returned (by pointer) to callers of functions. This use is frequent in real-world applications. Arrays created as variable-length arrays cease to exist when execution of their block ends.

  2. Arrays created with malloc can be resized with realloc. Variable-length arrays cannot be resized.

  3. As of the 2011 C standard, variable-length arrays are optional for C implementations to support. A general-purpose C implementation of any quality will support them, but the fact they are optional means code that is intended to be portable must either not use variable-length arrays or must guard against the lack of support by testing the preprocessor macro __STDC_NO_VLA__ and providing alternate code.

  4. Commonly, variable-length arrays are much more limited in size than arrays allocated with malloc. Variable-length arrays are generally implemented using stack space, and stacks are typically limited to some not-large number of mebibytes (although that can generally be increased when building an executable). For objects created with malloc, gibibytes of memory may be available in modern systems.

  5. If creation of an array does fail with malloc, NULL will be returned, and the programmer can easily write code to detect that and deal with it. If creation of a variable-length array fails, the common behavior is for the operating system to terminate the program with some memory error. (Various C implementations may provide means to intercept this error, but it is considerably more of a nuisance than testing the malloc return value for NULL, and it is not portable.)

like image 157
Eric Postpischil Avatar answered Oct 11 '22 14:10

Eric Postpischil


And I compiled and run it without any error. So, my question is why should I use malloc() really? Does this have something to do with the old and new C versions?

Stack-allocated arrays are not equivalent to buffers in the free-store (the heap, the memory area that malloc and calloc use).

  1. Assuming the array exists on the stack (which is implied as an automatic-variable) then your array cannot exceed the maximum stack size for your platform. On Linux with pthreads the default is 2 megabytes. The limit is similar on Windows.

  2. Because of scope and object lifetime: pointers to elements in an array that exist on the stack cannot live longer than the array they point into, which means you cannot return pointers to those arrays and elements after the scope they're declared in expires.

  3. VLA arrays are optional in C11. In C++ they're not part of the spec at all (i.e. they're vendor extensions) so your code won't be portable.

like image 38
Dai Avatar answered Oct 11 '22 14:10

Dai