4

In the following code I'm providing size of array at run time.

#include <stdio.h>

int main()
{
    int i;
    scanf("%d",&i);
    int a[i];
}

Please tell me the difference between the code above and code using malloc(). I know that array store is on the stack and dynamic memory (malloc, calloc etc) is on the heap. So is my code functioning similar to malloc? If not, please explain.

MD XF
  • 7,860
  • 7
  • 40
  • 71
pnmhtkr
  • 53
  • 5
  • The (unused) array `a` is a _variable length array_ or VLA and is probably stored on the stack, just like `i` is on the stack. Further, there's no way to 'free' that array other than exiting from the block (function) in which the array is defined. If you used `malloc()` et al, you'd have a pointer, and you'd need to `free()` the allocated array when you're done with it. If there was a loop around the code, you'd need to `free()` on each iteration; with the VLA, you don't have to worry about the freeing. VLAs are an unconditional part of C99 and an optional part of C11. – Jonathan Leffler Dec 01 '16 at 06:45
  • but as i know c11 and c99 can support this.i just wanted to know what is difference between dynamic memory allocation and declaring variable length of an array – pnmhtkr Dec 01 '16 at 06:48
  • 1
    You understand the difference in where the memory is allocated from right? Normal array and VLA will be allocated from the stack while dynamic allocation reserves memory from the heap. (though people argue about the use of those terms, they are generally used to make the distinction) – David C. Rankin Dec 01 '16 at 07:14
  • Usually, the stack is a lot smaller than the heap — the available stack size is often of the order of 1-8 MiB total, whereas the heap size can often go into multiple GiB total (especially with 64-bit systems). So, you can allocate much bigger arrays via `malloc()` et al than you can using the VLA mechanism. – Jonathan Leffler Dec 01 '16 at 16:29

2 Answers2

1

Apart from your code uses VLA which:

  • did not exist before C99
  • were introduced as a new feature in C99
  • are now an optional feature since C11

The difference is that automatic arrays (VLA or static size ones) are automatically release when they go out of scope, so you cannot return them from a function, while dynamically allocated ones persist until they are explicitely freed - which shall happen before you lose a pointer to them if you do not want a memory leak.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

The Above statement works in C99, but there are limitations of using this approach:

int a[i] is variable length array not the memory dynamically allocated, hence it will store on STACK instead of HEAP "which it does in case of malloc" hence there will be situation when somebody entered MAX_INT and your STACK memory limit is very less(Ex : Embedded Systems) then Stack Corruption might occur.

Sohil Omer
  • 1,171
  • 7
  • 14