C weird printf behavior

Advertisements

I just discovered a very weird trick that the c compiler is doing, it’s a very simple code I tried it in many online c compilers but the result is the same, which is driving me insane.

#include <stdio.h>

int main()
{
    char Buffer[10] = "0123456789";
    char ID[5] = "abcde";
    printf("%s",ID);

    return 0;
}

Take your time and try predict the result of the printf function, if you’re a human like me then I think the most obvious solution is "abcde", which is not correct! But if somehow you figured it out "abcde0123456789" then you’re consuming electricity to live.

How, just how is that possible, I’m only selecting the ID array to be printed, then WHY the Buffer one is printed with it too, it doesn’t make sense, even the ID array isn’t big enough to fit all that data, I’m really losing my mind here.

>Solution :

The format specification %s expects a pointer a string: sequence of characters terminated by the zero character '\0'.

However the both arrays

char Buffer[10] = "0123456789";
char ID[5] = "abcde";

do not contain strings. So the behavior of the call of printf invokes undefined behavior.

You should write

char Buffer[] = "0123456789";
char ID[] = "abcde";

or

char Buffer[11] = "0123456789";
char ID[6] = "abcde";

Pay attention to that string literals are stored as character arrays with addition zero character ‘\0’.

For example this declaration

char ID[] = "abcde";

in fact is equivalent to

char ID[] = { 'a', 'b', 'c', 'd', 'e', '\0' };

and this declaration

char ID[5] = "abcde";

is equivalent to

char ID[5] = { 'a', 'b', 'c', 'd', 'e' };

That is in the last case the zero character '\0' is not used as an initializer of the array ID.

Leave a ReplyCancel reply