4

why use malloc function when we can write the code in c like this :

int size;
printf("please the size of the array\n");
scanf("%d",&size);
int arr[size];

this eliminates the possibility of assigning garbage value to array size and is also taking the size of the array at run time ...

so why use dynamic memory allocation at all when it can be done like this ?

9
  • 2
    Because the array might be too large for a local variable to fit on the stack typically implemented in C. And because VLAs are not always implemented. Commented Mar 21, 2017 at 19:23
  • 7
    @yano VLAs were in C99 but are "optional" in C11. Commented Mar 21, 2017 at 19:25
  • 2
    And because you cannot declare VLAs at file scope. Also because you sometimes want to allocate memory with a lifetime extending beyond what a VLA provides -- for instance, if you want to return a pointer to it from the function that allocates it. Commented Mar 21, 2017 at 19:32
  • 1
    You need to check the return value of scanf: if (scanf("%d",&size) != 1) /* error */; Commented Mar 21, 2017 at 19:34
  • 3
    There is also the nice fact that if malloc fails you have a chance to handle that error, and it will be portable. Anything related to VLA failure can only be very platform specific. Commented Mar 21, 2017 at 19:40

4 Answers 4

3

This notation

int arr[size];

means VLA - Variable-Length Array.

Standard way they are implemented is that they are allocated on stack. What is wrong with it? Stack is usually relatively small - on my linux box it is only 8MB. So if you try to run following code

#include <stdio.h>

const int MAX_BUF=10000000;

int main()
{
    char buf[MAX_BUF];
    int idx;
    for( idx = 0 ; idx < MAX_BUF ; idx++ )
      buf[idx]=10;
}

it will end up with seg fault.

TL;DR version

PRO: VLA are OK for small allocations. You don't have to worry about freeing memory when leaving scope.

AGAINST: They are unsafe for big allocations. You can't tell what is safe size to allocate (say recursion).

Sign up to request clarification or add additional context in comments.

Comments

2

Besides the fact that VLA may encounter problems when their size is too large, there is a much more important thing with these: scope.

A VLA is allocated when the declaration is encountered and deallocated when the scope (the { ... }) is left. This has advantages (no function call needed for both operations) and disadvantages (you can't return it from a function or allocate several objects).

malloc allocates dynamically, so the memory chunk persists after return from the function you happen to be in, you can allocated with malloc several times (e.g in a for loop) and you determine exactly when you deallocate (by a call to free).

1 Comment

Thank you Jens for answering ...great help
1

Why to not use the following:

int size;
printf("please the size of the array\n");
scanf("%d",&size);
int arr[size];
  1. Insufficient memory. int arr[size]; may exceed resources and this goes undetected. @Weather Vane Code can detect failure with a NULL check using *alloc().

    int *arr = malloc(sizeof *arr * size);
    if (arr == NULL && size > 0) Handle_OutOfMemory();
    
  2. int arr[size]; does not allow for an array size of 0. malloc(sizeof *arr * 0); is not a major problem. It may return NULL or a pointer on success, yet that can easily be handled.

  3. Note: For array sizes, type size_t is best which is some unsigned integer type - neither too narrow, nor too wide. int arr[size]; is UB if size < 0. It is also a problem with malloc(sizeof *arr * size). An unqualified size is not a good idea with variable length array (VLA) nor *alloc().

  4. VLAs, required since C99 are only optionally supported in a compliant C11 compiler.

Comments

0

What you write is indeed a possibility nowadays, but if you do that with g++ it will issue warnings (which is generally a bad thing).

Other thing is your arr[size] is stored at stack, while malloc stores data at heap giving you much more space.

With that is connected probably the main issue and that is, you can actually change size of your malloc'd arrays with realloc or free and another malloc. Your array is there for the whole stay and you cannot even free it at some point to save space.

2 Comments

gcc allows VLA since an eternity. You only have to chose the suitable C standard on the command line.
it now seems I was completely wrong about gcc, I just get a warning and only because I have to use the older one as g++ and VLA is forbidden by iso c++

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.