Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Is it UB to read value of heap pointer after freeing?
Post
Is it UB to read value of heap pointer after freeing?
I've read in a guide that "the use of indeterminate memory for anything, including apparently harmless comparison or arithmetic, can have undefined behavior if the value can be a trap representation for the type."
The included quote from C11, section 6.2.4 §2, says:
The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.
The reason I'm mentioning the quote here is partially because I don't have a copy of the C standard.
Is reading the value of a pointer returned by a heap allocation function after its deallocation truly an instance of undefined behavior? (For example, debuggers may read and output the address to various I/O destinations: printer, screen, disk, network, etc.)
Consider the following program:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
void *pointer = malloc(1);
if (pointer == NULL) return 1;
free(pointer);
printf("%p\n", pointer); /* Reading the address. Undefined behavior? */
return 0;
}
Does the specification for this differ across ANSI C and other versions of ISO C?

1 comment thread