Why do characters after %s in printf replace the starting characters

Why do characters after %s in printf replace the starting characters

I'm learning C and trying to debug with printf calls.

But, when I format a string with %s and have characters immediately after, they end up replacing the characters at the beginning.

Example: user_agent = foobar/1.2.3

printf("AGENT: %s:\nHELLO", user_agent);

The output is:

:GENT: foobar/1.2.3
HELLO

Whereas I would have expected the output to be:

AGENT: foobar/1.2.3:
HELLO

Why does the : after the %s replace the A at the beginning?

I can't figure out how to word this question, so my attempts at googling the issue have not yielded any results.

Answer

Can't reproduce your question, you might want to try recompiling the same test code snippet with a different C compiler to see if the issue persists

gcc -o test test.c && ./test
clang -o test test.c && ./test
cl test.c && test.exe

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions