1

For example,

int a = 6;
printf("%p", &a);

this would print the address of the pointer of a right? but what if we print without &?

int a = 6;
printf("%p", a);

Can someone please tell me what it prints out?

승기유
  • 133
  • 9

2 Answers2

3

This is undefined behavior, because %p expects a void*

printf("%p", a);

Adding an explicit conversion is allowed, but the behavior is implementation-defined:

printf("%p", (void*)a);

"Implementation-defined" means that the compiler is free to do whatever it wants when converting an int to void*. See this Q&A for exact quotes from the standard.

In many implementations you would see a pointer assigned the numeric value of int (demo 1). Other implementations would warn you that the behavior is meaningless. If you treat warnings as errors, the code would fail to compile (demo 2).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • "compiler is free to do whatever it wants when converting an int to void*." Well, no. Compiler must do as defined by implementation. It won't depend on optimizations for example (on any sane implementation). – hyde Apr 15 '18 at 10:41
  • 1
    @hyde `loop { putchar('?'); }`, what do you think a compiler is if it's not the "implementation" ? Did you mean operating system ? It's very different concept ! Clang can do what it want and GCC can do what it want. "compiler is free to do whatever it wants when converting an int to void*." is completely correct that exactly the definition of implemented behavior. – Stargateur Apr 15 '18 at 10:55
  • @Stargateur What I meant is, if it would be undefined behavior, compiler could do whatever it wants. If it is implementation defined behavior, compiler must do exactly as it is defined to do, which you can find out and rely on, and take advantage of for example in configure scripts and using #ifdefs etc (as long as implementation doesn't change, which it generally doesn't often, because unfortunately there is a lot of code which depends on implementation defined behavior). – hyde Apr 16 '18 at 05:51
2

According to the C standard, it's undefined behavior to send wrong matching type argument to printf(). And int != void *, so it's undefined behavior.

Each of the following statements applies unless explicitly stated otherwise in the detailed descriptions that follow: If an argument to a function has an invalid value (such as a value outside the domain of the function, or a pointer outside the address space of the program, or a null pointer, or a pointer to non-modifiable storage when the corresponding parameter is not const-qualified) or a type (after promotion) not expected by a function with variable number of arguments, the behavior is undefined.

Source


By the way, that why you should write printf("%p", (void *)&a);

warning: format specifies type 'void *' but the argument has type 'int *' [-Wformat-pedantic]
printf("%p", &a);
        ~~   ^~
Stargateur
  • 24,473
  • 8
  • 65
  • 91