Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printf with no arguments explanation

Tags:

c

printf

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.

like image 894
sbnation Avatar asked Dec 26 '14 18:12

sbnation


People also ask

What is a function with no arguments called?

A nullary or niladic function.

What is argument in printf?

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().

How does printf know how many arguments?

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.

What is the problem with printf in C?

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.


2 Answers

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.

like image 144
ouah Avatar answered Oct 25 '22 07:10

ouah


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.

like image 29
Basile Starynkevitch Avatar answered Oct 25 '22 09:10

Basile Starynkevitch