Home > Back-end >  Why can I assign items to an array that has a length of 0?
Why can I assign items to an array that has a length of 0?

Time:09-19

So I have this code:

#include <stdio.h>
int main()
{
printf("enter character\n>>>");
char input[0];


scanf("%5s",input);
printf("%s",input);
}

that excepts 5 chars from the user. I am new to C and this one thing makes no sense to me. Why does gcc allow me to compile a program that assigns values to an array with a length of 0? Surely this is not possible? Please explain.

CodePudding user response:

Your compiler ought to reject the declaration as invalid

If the expression is a constant expression, it shall have a value greater than zero. (6.7.6.2).

However, as @Joshua points out below, some compilers support this feature as an extension:

Declaring zero-length arrays is allowed in GNU C as an extension (info gcc; 6.18)

gcc -pendatic -pedantic-errors will generate an error and only warning without -pedantic-errors.

scanf() and printf() will also be undefined behavior.

CodePudding user response:

C doesn't check for buffer overrun.

This bears repeating.

C doesn't check for buffer overrun.

This has been a source of bugs for a very long time; but also it's inherent in C and cannot be changed.

There are some simple cases where the compiler can detect buffer overrun (usually with optimizations enabled as well) but in the general case it cannot; nor will it generate any runtime checks. It will just do something unexpected. This is usually a security problem if you let it.

You must check yourself that you don't overrun buffers.

CodePudding user response:

This program causes undefined behaviour. Anything can happen, including the appearance of "correct behaviour." C is not the kind of language that can protect you from every potential memory management pitfall.

  • Related