Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does casting to void* does when passing arguments to variadic functions?

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.

like image 832
Calmarius Avatar asked Apr 25 '26 12:04

Calmarius


1 Answers

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

like image 157
haccks Avatar answered Apr 27 '26 01:04

haccks