I understand that if printf is given no arguments it outputs an unexpected value.
Example:
#include <stdio.h>
int main() {
int test = 4 * 4
printf("The answer is: %d\n");
return 0;
}
This returns a random number. After playing around with different formats such as %p, %x etc, it doesn't print 16(because I didn't add the variable to the argument section) What i'd like to know is, where are these values being taken from? Is it the top of the stack? It's not a new value every time I compile, which is weird, it's like a fixed value.
A nullary or niladic function.
The parameters passed into printf() are known as arguments; these are separated commas. C Program 2.1 contains a printf() statement with only one argument, that is, a text string. This string is referred to as the message string and is always the first argument of printf().
The printf function uses its first argument to determine how many arguments will follow and of what types they are. If you don't use enough arguments or if they are of the wrong type than printf will get confuses, with as a result wrong answers.
The printf functions are implemented using a variable-length argument list. Arguments specified after the format string are passed using their inherent data type. This can cause problems when the format specification expects a data object of a different type than was passed.
printf("The answer is: %d\n");
invokes undefined behavior. C requires a conversion specifier to have an associated argument. While it is undefined behavior and anything can happen, on most systems you end up dumping the stack. It's the kind of trick used in format string attacks.
It is called undefined behavior and it is scary (see this answer).
If you want an explanation, you need to dive into implementation specific details. So study the generated source code (e.g. compile with gcc -Wall -Wextra -fverbose-asm
+ your optimization flags, then look into the generated .s
assembly file) and the ABI of your system.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With