4

Here's a quick question.

When you use format specifiers in the string you want to print, but don't list any values which you want to replace the placeholders with after the string, you get seemingly random numbers such as 2627389, 6278253 etc. as the output. Here's an example:

printf("%d %d %d");

The output would look something like:

2621244 4352722 1426724

I was wondering why this happens, and what those numbers mean. If you have an idea, it would really help. Thanks.

2
  • 4
    It's undefined behaviour, but what commonly happens in that situation is that printf just grabs the bytes that are where it expects its arguments, be that on the stack or in some registers. If it expects some pointers, a crash is not unlikely. Commented Nov 4, 2012 at 1:43
  • possible duplicate of Wrong number of parameters to printf leads to strange results Commented Nov 4, 2012 at 10:42

2 Answers 2

3

In most cases, those numbers are "random" values that just happen to be in the stack or in registers depending on the processor. In the olden days, all the parameters to a function were passed on the stack, pushed in reverse order. For printf(), the first parameter, and the last pushed, would be the format string. In your example, the stack would look like:

sp[0] = "%d %d %d"

printf would grab the top of the stack (the format string) and parse it, grabbing additional parameters in higher stack locations, format them according to the format string and output them appropriately.

If you had a well formed printf call, e.g. printf("%d %d %d", 1, 2, 3), then the stack would look like

sp[3] = 3
sp[2] = 2
sp[1] = 1
sp[0] = "%d %d %d"

printf would do what you expect: grab the appropriate stack location for each format specifier and format it appropriately. When you don't pass the other parameters, whatever happens to be in those stack locations are output instead, hence the "random" values.

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

1 Comment

You made it very clear how printf works, thank you very much.
1

It's called "undefined behavior" ;)

At best, you'll get garbage. At worst, you can actually crash the program.

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.