Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it valid to access a pointer to a "dead" object?

People also ask

Can a pointer be used after free?

UAFs and Dangling PointersUse-after-free is the result of dereferencing a pointer that points to an object that had already been freed (also called a dangling pointer): Two common reasons that lead to dangling pointers are: Not updating the reference count of a currently in-use object.

Can a pointer point one past the end of an object?

it is possible for a pointer to an object and a pointer one past the end of a different object to hold the same address.

What happens to a pointer when you free it?

The function free takes a pointer as parameter and deallocates the memory region pointed to by that pointer. The memory region passed to free must be previously allocated with calloc , malloc or realloc . If the pointer is NULL , no action is taken.


Example 2 is invalid. The analysis in your question is correct.

Example 1 is valid. A structure type never holds a trap representation, even if one of its members does. This means that structure assignment, on a system where trap representations would cause problems, must be implemented as a bytewise copy, rather than a member-by-member copy.

6.2.6 Representations of types

6.2.6.1 General

6 [...] The value of a structure or union object is never a t rap representation, even though the value of a member of the structure or union object may be a trap representation.


My interpretation is that while only non-character types can have trap representations, any type can have indeterminate value, and that accessing an object with indeterminate value in any way invokes undefined behavior. The most infamous example might be OpenSSL's invalid use of uninitialized objects as a random seed.

So, the answer to your question would be: never.

By the way, an interesting consequence of not just the pointed-to object but the pointer itself being indeterminate after free or realloc is that this idiom invokes undefined behavior:

void *tmp = realloc(ptr, newsize);
if (tmp != ptr) {
    /* ... */
}