Question

I have

void *ptr = malloc(9);
printf("%X", ptr); //this shows the value of memory pointed to by ptr

//I want to try to see what ever is at the memory location by dereferenced ptr
printf("%c", (*ptr)); // try to dereference the pointer

this however causes a compiler error... how can I see the value pointed to be the memory allocated in ptr, I know it'll be some garbage value, I just want to see

Was it helpful?

Solution

void *ptr = malloc(9);
printf("%X", ptr); //this shows the value of memory pointed to by ptr

The previous line shoud have been:

printf("%p", ptr); //this shows the value of ptr

"%X" is for int, using it for pointers invokes UB, meaning anything can happen.

//I want to try to see what ever is at the memory location by dereferenced ptr
printf("%c", (*ptr)); // try to dereference the pointer

Because voidis an incomplete type, it cannot be dereferenced. Cast to a pointer of the desired type first, then we can talk. For char that line would be:

printf("%c", *(char*)ptr); // try to dereference the pointer

But if you try to use a value before assigning it, beware of trap representations and other fun stuff.

Some more tips for you:

  • Always compile with all warnings enabled. Add options "-Wall -Wextra -pedantic"
  • Decide on C or C++. This example works same for both though.
  • Get the standard, or at least the last working draft. Wikipedia has pointers to them.
  • If you post a question here, try to include a short, concise example, which can be compiled immediately. This time it was good anyway.

OTHER TIPS

It can't be dereferenced because you have declared it as void and void has no size. You can dereference it if you cast it to something which has a size, though. For example, printf("%c", *(char *)ptr);

you can do like this printf("%c\n", *((char*)ptr));

The compiler has now idea what kind of data to look for when it dereferences ptr. You can do a typecast to char*. printf("%c", *((char*)ptr));

As others have noted, you can surely do this in practice, but it is undefined behavior:

For C, E.g. in ISO/IEC 9899:TC3, WG14/N1256 Annex J.2.1

The behavior is undefined in the following circumstances:
...
The value of the object allocated by the malloc function is used (7.20.3.3).
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top