Consider
int main()
{
char* p = malloc(5);
printf("%td", &p[5] - &p[0]); /*one past the end is allowed*/
free(p);
printf("%td", &p[5] - &p[0]); /*I no longer own p*/
}
Is the behaviour of this code defined? Are you allowed to perform pointer arithmetic on an array that you no longer own?
Yes, you're usually allowed to do that on many compilers in many environments.
You have to keep in mind, however, that the ISO C standard doesn't have any requirement for your language when you do it, however: it doesn't define the behavior any use of a pointer whose value is "indeterminate". According to ISO C, the value of p
after free(p)
has essentially the same status as if it were uninitialized.
Are you looking for the language lawyer answer, or the practical answer?
The language lawyer answer is, no, it's undefined.
The practical answer is: yes, it'll probably work, but it's a bad idea. I would always compute the difference (and store it in a variable if necessary) before freeing the pointer.
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