Phil
Phil

Reputation: 179

C++ sprintf output order is incorrect

I have the following code that should output;

1234 : abcd

However I get

1234abcd : 
        char string1[4];
        sprintf(string1,"1234");

        char string2[4];
        sprintf(string2,"abcd");

        sprintf(text_string,"%s : %s",string1,string2);

How can I get the sprintf to output in the correct order? I tried adding the " : " as a third string in the middle, but was still added to the end.

Upvotes: 2

Views: 225

Answers (1)

You have undefined behavior: The sprintf() calls both write five characters (four characters payload + one terminating null byte) to an array that is only four characters long. After the first call to sprintf() all bets are off.


That said, what happens is, that the second sprintf() call overwrites the terminating null character that was written by the first sprintf() call, and thus the final sprintf() keeps printing through the second string until it finds that string's terminating null byte. I have no clue why the second string does not appear a second time in the output, but I don't have to: Since you have undefined behavior, anything is allowed to happen. Including the appearance of pink elephants...

Upvotes: 2

Related Questions