2
#include <stdio.h>

char s[3] = "Robert";
int main()
{
    printf("%s",s);
}

Output: Rob

How does this get printed properly? The string is not null terminated. I saw the assembly. It used .ascii for storing "Rob" which is not null terminated. I expected some garbage along with Rob to be printed. Can someone explain me this behaviour?

10
  • 11
    It is simply undefined behaviour. Commented Apr 26, 2014 at 22:18
  • 1
    Probably because you got lucky and the next byte in memory after s is \x00. Commented Apr 26, 2014 at 22:18
  • 1
    I am just trying to learn how character arrays and literals are stored. Commented Apr 26, 2014 at 22:19
  • 4
    FWIW, this was allowed in C. C++11 § C.1.7 [diff.decl] says In C++, when initializing an array of character with a string, the number of characters in the string (including the terminating ’\0’) must not exceed the number of elements in the array. In C, an array can be initialized with a string even if the array is not large enough to contain the string-terminating ’\0’ Commented Apr 26, 2014 at 22:25
  • 1
    Thanks Chris for pointing to the rules.. I tried out in c++. It does give error. g++ enforces it. The more I learn about about c and c++ , i realize that they are different in many aspects. Commented Apr 26, 2014 at 22:29

1 Answer 1

4

Your "Rob" has been stored in an extra section of the executable. The sections in an executable are aligned, i.e. the section with the data is padded with 0 until the next section. So printf got "its" 0 from the section padding. To illustrate:

#include <stdio.h>

char dummy[] = "ocop";
char s[3] = "Robert";
char second[] = "in Hood";
int main( void )
{
    printf("%s",s);
    return 0;
}

Output (MinGW-GCC w/o optimization): Robin Hood
Output (MinGW-GCC with optimization): Robocop

Now there is no 0 from the padding but the begin of the next string which will be outputted as well.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.