1

Following piece of code compiles in gcc. But it is not correct way of writing as it surpasses the use of malloc function. What is the problem in this code?

#include<stdio.h>
main()
{
     int n;
     scanf("%d",&n);
     int a[n];
}
2
  • 1
    Batter int *a = (int*)malloc(sizeof(int)*n); Commented Apr 5, 2014 at 6:16
  • int a[n]; is fine as long as you do a little sanity checking (or your users don't do anything insane, like enter a negative number, or try to put more than 8 MiB on the stack — more or less depending on ulimit -s ). Commented Apr 5, 2014 at 6:47

3 Answers 3

5

your code is legal ISO C99 code. It's not C89 ANSI compliant: if you are stuck with compatibility rules, because of old compilers or company policies, you need to use malloc().

More importantly, in C99, using your definition, the array is allocated on stack, that is usually a limited resource, while with malloc() it's allocated in the heap.

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

Comments

1

Your array is a variable length array (VLA). This is an advanced feature of C, introduced in the C99 version of the standard.

The problem with VLAs is that they can easily overflow the stack. Unless you have a specific reason to use a VLA, use dynamic memory with malloc and avoid the risk of stack overflow.

Your main declaration is wrong. It should be

int main(void)

Comments

0

"...it is not correct way of writing as it surpasses the use of malloc function..." - what is that supposed to mean? According to the rules of modern C language, the only problem with your code is the missing int in the declaration of main. I.e. it has nothing to do with any malloc.

It can be said that your code is self-contradictory in a sense that it uses a perfectly valid C99 feature - variable length array int a[n] - but at the same time relies on an obsolete feature of C89/90 - implied int in the declaration of main, which is no longer supported by C99.

You need to decide which version of C language you are trying to use - C89/90 or C99. Once you make that decision, we'll be able to discuss the correctness of your code.

1 Comment

Worth mentioning that VLA support was only required between 1999 and 2010 ; now they are optional.

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.