Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-byte-off pointer still valid in C?

I might be mistaken, but I seem to remember that for a given memory allocation, e.g.

char *p = malloc(4);

the pointer p is a valid pointer for all bytes within the allocation and for the first byte beyond that allocation.

Thus, to access memory through the pointer p only offsets p[0] .. p[3] are valid. But for pointer comparison &( p[4] ) would also be be a valid pointer.

Is that correct, and where in the C Standard (link) does it say so? It seems that 6.5.9 p6 might hint into the right direction for the answer, but it's a bit fuzzy still.

like image 562
Jens Avatar asked Mar 12 '14 06:03

Jens


1 Answers

&p[4], or p + 4 is a valid pointer, but it can't be derefrenced.

C11 6.5.6 Additive operators

[...] 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. If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.

like image 191
Yu Hao Avatar answered Sep 24 '22 02:09

Yu Hao