Free pointer arithmetic

After reading the answers to this SO question , I found out that pointer arithmetic is out-of-bounds 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, or one after the last element of the array, the evaluation should not lead to overflow; otherwise, the behavior is undefined.

Does this facility void the warranty? 7.20.3.2 The “free function” does not seem to mention this, simply saying that “space is freed”. Since 6.5.6 specifically mentions overflow, this seems like a problem with integer overflow that will not affect for free. Is arithmetic a pointer to an object an act of "referring to it"?

In other words, it is:

char *foo = malloc(10);
free(foo);
foo++;

Undefined? Or is another overflow used?

+3
source share
3 answers

C99 §6.2.4 states:

The value of the pointer becomes undefined when the object it points to before the end of its life.

§7.20.3 describes the lifetime of selected objects created using malloc():

The lifetime of the selected object continues from allocation to release.

So, formally speaking, the value of the pointer foobecomes indefinite after free(), and therefore it can no longer be said that it points to any object. Therefore, the increment behavior is undefined.

+5
source

undefined.

+1

Here foois the pointer variable that will store the address char. In fact, this address will be a virtual address.

So, if we perform any arithmetic of a pointer to a variable foo, this will increase the values ​​in accordance with the type of the pointer variable. This will not be considered undefined behavior.

-1
source

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


All Articles