-2
main()
{
        int n;
        scanf("%d",&n);
        char a[n];
}

In this case are we not allocating memory during runtime to 'a' then why use malloc??

Morpfh
  • 4,033
  • 18
  • 26
  • In fact you are, internally compiler translates it to alloca() which attempts to allocate storage on stack if possible, if not, it can use regular malloc. In second case it will call regular free() when stack frame collapses. – Anonymous Dec 20 '14 at 21:31
  • I do not think that this question is a dupe of the linked question. – haccks Dec 20 '14 at 21:32
  • Disagree that this is a dup. There are specific issues with variable-length arrays which are not covered in the other answer. – Tony Dec 20 '14 at 21:41

1 Answers1

1

char a[n] is not allowed in the older C standard. It is permitted in C99, but only for automatic variables (i.e. on the stack, as in your example). If you want, say, a global variable, you will need to use malloc et. al. to comply with the standard.

Edited to provide some evidence

There is a helpful series of articles about variable-length arrays in C. From the second article, "VLAs must be auto (as opposed to static or extern) variables in a block."

Tony
  • 1,645
  • 1
  • 10
  • 13