Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

It's called "undefined behavior" ;)

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top