I was experimenting with the following C code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a = 5;
int *ptr = &a;
printf("Data stored: %d\n", *ptr); // Simply prints 5.
printf("Address of variable a: %p\n", (void*) &a);
printf("Address stored in ptr: %p\n", (void*) ptr);
return EXIT_SUCCESS;
}
I compiled the program with:
gcc -Wall -Wextra -Wconversion -pedantic -std=c11 -fsanitize=address -fsanitize=undefined example-1.c -o example-1
I understand that the %p
format specifier expects an object address (using &
or a valid pointer) but when I compile the code without typecasting to void*
it generates a warning:
example-1.c: In function ‘main’:
example-1.c:8:37: warning: format ‘%p’ expects argument of type ‘void *’, but argument 2 has type ‘int *’ [-Wformat=]
printf("Address of variable a: %p\n", &a);
~^ ~~
%ls
example-1.c:9:34: warning: format ‘%p’ expects argument of type ‘void *’, but argument 2 has type ‘int *’ [-Wformat=]
printf("Data stored in ptr: %p\n", ptr);
~^
%ls
So, I naturally typecast the arguments to void*
and then the program works fine, but I cannot make any logical inference about what is actually happening.