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.
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.
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) {
/* ... */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With