문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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).
...
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top