0

I am using gcc compiler on Linux Redhat. I am surprised why there is 2 characters difference in output of a[5] and a[6] (Maya and Mayank) though their sizes differ only 1 byte.

char a[5]="Mayank";
char b[6]="Mayank";
char c[7]="Mayank";

printf("%s\n",a);
printf("%s\n",b);
printf("%s\n",c);

Output:

Maya
Mayank
Mayank
janisz
  • 6,292
  • 4
  • 37
  • 70

2 Answers2

8

The first two printf calls have undefined behaviour since neither a nor b include a terminating NUL character (c does, so the last printf() would be fine on its own).

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Only first is Undefined `char b[6]="Mayank";` is valid in C (but bot in C++), that is same as `char b[6] = {'M', 'a', 'y', 'a', 'n', 'k'}`. – Grijesh Chauhan Dec 24 '13 at 09:41
  • 2
    @GrijeshChauhan: Is it? There are seven characters in `"Mayank"`, counting the nul. The array is too small to hold them all. – cHao Dec 24 '13 at 09:42
  • 2
    @GrijeshChauhan: How so? Where does the NUL required by `%s` come from? – NPE Dec 24 '13 at 09:42
  • 2
    @GrijeshChauhan your statement is not true. – Ivaylo Strandjev Dec 24 '13 at 09:43
  • 1
    this is special case in C but not valid in C++. @IvayloStrandjev try with `gcc -Wall -pedantic` you willget waring for first but not for second – Grijesh Chauhan Dec 24 '13 at 09:44
  • @NPE I had same confusion some days back and I had a conversation with [Keith Thompson](http://stackoverflow.com/users/827263/keith-thompson). You can [read here](http://stackoverflow.com/questions/17790127/what-is-meant-by-char-temp3/17790207#comment27226774_17790207) – Grijesh Chauhan Dec 24 '13 at 09:47
  • 2
    @GrijeshChauhan: You are missing the point, which is that **the `%s` in `printf()` requires a NUL terminator.** If there's no NUL, the behaviour of `printf()` is undefined. – NPE Dec 24 '13 at 09:49
  • 1
    I don't give a damn what GCC says. The nul *must* be there, or you end up with UB when you try to treat the char array as a string (as `printf` does). And there's not enough room for it in a 6-element array, so it's not there. – cHao Dec 24 '13 at 09:49
2
char a[5]="Mayank";

You are filling an array of 5 elements with a string that contains 7 elements (7 charachters).

"Mayank" contains 6 charachters + a null charachter ('\0') at the end of the string

So this is undefined behaviour. So you will get a random output.

Same thing for

char b[6]="Mayank";

And it's OK for the

char b[7]="Mayank";
MOHAMED
  • 41,599
  • 58
  • 163
  • 268