Define a char array with a size which does not count the null character

Viewed 72

I am asked to say whether the following piece of code triggers any error or warning:

char string[5] = "hello";

I have tested it on my computer and it worked fine (no error/warning and printf gave the expected value ("hello") and strlen gave the expected value (5)). However, I would be tempted to say that this yields some kind of undefined behaviour. I suppose this is considered a bad practice anyway, but can it cause an error since we are not explicitly allowing a byte for the null character?

2 Answers

It's allowed. Source: K&R C, ANSI C version. "A char array may be initialized with a string of that many characters." This results in a string that is not null terminated--use with caution. This means that printf("%s", string); isn't defined but printf("%.5s", string); is.

Appearing to work is a possible result of undefined behavior. In fact on examples like this, the last thing in the file's .data region will be the string, which then gets padded with zeros to match the machine alignment. On the stack, when the program first starts up, uninitialized memory in main tends to have the same condition of being zeroed (this was not always the case, and in no case should any code ever depend on this). Thus resulting in everything appearing to work. But when the program gets bigger, it stops working for no apparent reason because memory layout or initialization changed.

In C the compiler will allow this, as equivalent to

char string[5] = { 'h', 'e', 'l', 'l', 'o' };

Note that there will not be a string null-terminator added.

See e.g. this array initialization reference.

Also note that this is one of the many places where C differs from C++, where this is not allowed.

Related