C: Why does gcc allow char array initialization with string literal larger than array?

Posted by Ashwin on Stack Overflow See other posts from Stack Overflow or by Ashwin
Published on 2012-11-21T10:07:58Z Indexed on 2012/11/22 17:00 UTC
Read the original article Hit count: 142

int main()
{
    char a[7] = "Network";
    return 0;
}

A string literal in C is terminated internally with a nul character. So, the above code should give a compilation error since the actual length of the string literal Network is 8 and it cannot fit in a char[7] array.

However, gcc (even with -Wall) on Ubuntu compiles this code without any error or warning. Why does gcc allow this and not flag it as compilation error?

gcc only gives a warning (still no error!) when the char array size is smaller than the string literal. For example, it warns on:

char a[6] = "Network";

[Related] Visual C++ 2012 gives a compilation error for char a[7]:

1>d:\main.cpp(3): error C2117: 'a' : array bounds overflow
1> d:\main.cpp(3) : see declaration of 'a'

© Stack Overflow or respective owner

Related posts about c++

Related posts about c