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'
Initializing a char array with a string literal that is larger than it is fine in C, but wrong in C++. That explains the difference in behavior between gcc and VC++.
You would get no error if you compiled the same as a C file with VC++. And you would get an error if you compiled it as a C++ file with g++.
The C standard says:
(Section 6.7.9 of the C11 draft standard, actual wording in final standard might be different.)
This means that it’s perfectly correct to drop the termination character if the array doesn’t have room for it. It’s maybe unexpected, but it’s exactly how the language is supposed to work, and a (at least to me) well-known feature.
On the contrary, the C++ standard says:
(8.5.2 of the C++ 2011 draft n3242.)