Are you allowed to do pointer arithmetic on an array that you no longer have?

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 behavior of this code defined? Are you allowed to do pointer arithmetic on an array that you no longer have?

+4
source share
2 answers

Yes, you are usually allowed to do this in many compilers in many environments.

However, you should bear in mind that the ISO C standard does not require any requirements for your language when you do this: it does not define behavior by any use of a pointer whose value is “undefined.” According to ISO C, the value pafter free(p)has essentially the same status as uninitialized.

+4
source

?

: no, it undefined.

: , , , , . ( , ), .

+3

Source: https://habr.com/ru/post/1681609/


All Articles