Anup Buchke
Anup Buchke

Reputation: 5520

Not Null Terminated character array

#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?

Upvotes: 2

Views: 242

Answers (1)

rkhb
rkhb

Reputation: 14409

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.

Upvotes: 4

Related Questions