6

I'm trying to explain to someone why they have a dangling pointer and how free actually works (and that pointers are values and thus are passed-by-value), but for that I think I need a way to print pointers that isn't "indeterminate" (as is the case with printf("%p", ptr)).

Would memcpy do the trick?

char buf1[sizeof(char *)];
char buf2[sizeof(char *)];
char *malloced = malloc(10);
memcpy(buf1, &malloced, sizeof(char *));
free(malloced);
memcpy(buf2, &malloced, sizeof(char *));
for (int i=0; i<sizeof(char *); i++) {
    printf("%hhd %hhd / ", buf1[i], buf2[i]);
}
  • 3
    Pretty sure there’s no legal way to do anything with a dangling pointer, so just go ahead and %p. – Ry- Jul 14 '18 at 23:24
  • I can't figure out what you mean by "indeterminate". Can you clarify the problem you're trying to solve? What do you want to print out? What more can you say about a dangling pointer other than that it's dangling? – David Schwartz Jul 14 '18 at 23:24
  • @DavidSchwartz I want a visual aid that shows the pointer's value is the same before and after the call to free (since pointers are pass-by-value, so you're copying the value into free, and free can't modify your copy of the value). – SoniEx2 Jul 14 '18 at 23:26
  • @DavidSchwartz Reading a pointer value (let alone dereferencing it) after it was deleted is UB, and OP is trying to work around that. – HolyBlackCat Jul 14 '18 at 23:26
  • 1
    free is defined as void free(void *ptr) not void free(void **ptr_to_ptr). it cannot actually change the pointer as far as I'm aware. – SoniEx2 Jul 14 '18 at 23:50
8

According to a strict reading of the C standards, you can't do anything with a dangling pointer: “indeterminate”, the state of memory that holds a dangling pointer, also describes the contents of uninitialized automatic variables, and these may have different values if you read them twice in a row(*).

The only way around the issue is to convert the pointer to uintptr_t while it is still valid. The result of the conversion is an integer and has the properties of integers:

#include <stdint.h>
...
char *malloced = malloc(10);
uintptr_t ptr_copy = (uintptr_t) malloced;
...
free(malloced);
// it is valid to use ptr_copy here to display what the address was.
printf("The pointer was at: %" PRIxPTR "\n", ptr_copy);

(*) The C11 standard distinguishes automatic variables the address of which is not taken (“that could have been declared with the register storage class”), but Clang does not care.

To answer specifically your suggestion of using memcpy, note that memcpy of indeterminate memory produces indeterminate memory.

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.