Rattata 2me
Rattata 2me

Reputation: 37

The "%p" printf parameter

I have this code:

#include <stdio.h>
#include <string.h>

void main(){
       printf("%p");
}

This is the output: 0x7ffdd9b973d8

I know %p stands for pointer and when using it as for example

#include <stdio.h>
#include <string.h>

void main(){
 int i = 0;
 printf("%p", i);
}

it returns the pointer address of i. But my question is what does it return when not adding any other argument in the printf function just printf("%p")

Upvotes: 0

Views: 3557

Answers (3)

AnT stands with Russia
AnT stands with Russia

Reputation: 320481

The behavior of

printf("%p");

is undefined. When you specify a %p format in the format string, the corresponding argument of void * (or char *) type shall be present in the argument list.

Upvotes: 4

David Schwartz
David Schwartz

Reputation: 182761

But my question is what does it return when not adding any other argument in the printf function just printf("%p");

Anything. Nothing. Random junk. Maybe it crashes.

There is no way to know without investigating a specific combination of compiler, CPU, platform, libraries, execution environment, and so on. There is no rule that requires it to operate any particular way.

Upvotes: 4

Mad Physicist
Mad Physicist

Reputation: 114310

Trash. printf uses a variable-length argument list. It uses the format string to determine how many arguments you actually passed. If you did not actually pass anything in, it will still read from basically arbitrary portions of memory as though you did. The result is undefined/trash.

Some compilers will be able to catch this situation with a warning because the printf family of functions is so popular. Some cases may crash your system if the function tries to read from memory you do not have access to. There is no way to tell how it will behave next time even if you have obtained a certain result.

Upvotes: 4

Related Questions