While reading the answers to this SO question, I learned that out-of-bounds pointer arithmetic is undefined. Indeed, according to C99 6.5.6 paragraph 8
If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.
Does freeing that object invalidate that guarantee? 7.20.3.2 "The Free Function" Doesn't seem to mention it, simply mentioning that "the space is deallocated". Since 6.5.6 specifically mentions overflow, it seems like an integer overflow issue, which free wouldn't affect. Is arithmetic on a pointer to an object an act of "referring to it"?
In other words, is:
char *foo = malloc(10);
free(foo);
foo++;
Undefined? Or is the usage of "overflow" a different one?
C99 §6.2.4 says:
The value of a pointer becomes indeterminate when the object it points to reaches the end of its lifetime.
§7.20.3 describes the lifetime of allocated objects, as created by malloc():
The lifetime of an allocated object extends from the allocation until the deallocation.
So, formally speaking, the value of the pointer foo becomes indeterminate after the free(), and therefore can no longer be said to point to any object. The behaviour of the increment is therefore undefined.
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