문제

There is another question that discusses something like this: When printf is an address of a variable, why use void*?, but it only answers why shouldn't you print pointers as ints.

Another question discusses you should always cast pointers to void* when passing them to variadic functions: Argument conversion: (normal) pointer to void pointer, cast needed?. It says if you don't do so you invoke undefined behavior, but it doesn't go beyond that.

Indeed:

      if (pIReport4 == NULL)
      {
          printf("It's NULL but when I print it, it becomes: %p\n", pIReport4);
          printf("It's NULL but when I print it and cast it into (void*), it becomes: %p\n", (void*)pIReport4);
          printf("And NULL is: %p\n", NULL);
      }

Prints:

It's NULL but when I print it, it becomes: 0xc68fd0
It's NULL but when I print it and cast it into (void*), it becomes: (nil)
And NULL is: (nil)

pIReport4 is a non-void pointer.

It's clear it's pushing something else into the stack if you don't do the cast. What might it push? Why?

What's the rationale of making passing non-void pointers undefined behavior? It doesn't make sense to me...

I always thought pointer casting is just a hint to compiler how to interpret the pointed data when reading or writing it. But when passing just the pointer value I would expect that it passes the same sequence of bytes regardless of type.

도움이 되었습니까?

해결책

As the answer in the second link explains that

For printf, p conversion specifier requires a void * argument. If the argument is of a different type, the function call invokes undefined behavior. So if the argument of pis an object pointer type, the (void *) cast is required.

That is, since your code snippet invokes undefined behavior, you can get anything, either expected or unexpected result. The result you are getting may also vary compiler to compiler. On my compiler (GCC 4.8.1) it is giving the result:
enter image description here

다른 팁

By default all arguments to variadic functions are passed as the type of the variable passed.

You did not mention what type pIReport4 is, but assuming it's for example an int then it will be passed as 4 bytes on the stack. If you happen to be on a 64-bit system then sizeof(void *) is 8 bytes. Thus printf will read 8 bytes from the stack and there is your undefined behaviour.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top