Search code examples
arrayscassign

Why can I assign items to an array that has a length of 0?


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.


Solution

  • 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.