Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are you allowed to perform pointer arithmetic on an array that you no longer own?

Tags:

c

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?

like image 276
Fitzwilliam Bennet-Darcy Avatar asked Mar 08 '23 14:03

Fitzwilliam Bennet-Darcy


2 Answers

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.

like image 187
Kaz Avatar answered Mar 29 '23 23:03

Kaz


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.

like image 21
Steve Summit Avatar answered Mar 30 '23 00:03

Steve Summit