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.
&p[4]
, orp + 4
is a valid pointer, but it can't be derefrenced.This answer assumes that
p
is achar *
.The pointer
p + 4
(or&( p[4] )
is valid for comparison top + N
whenN
is in {0, 1, 2, 3, 4} with<
,<=
, or==
. This is noted in C11 6.5.8:5:However,
p+4
is not valid for comparison with==
to, say,&X
whereX
is another variable. This is (to the best of my C-standard deciphering) unspecified behavior. (And of course none ofp + N
is valid for comparison with<=
to&X
.)Strictly speaking, the standard does not seem to say anywhere that
p + 4 == NULL
is defined either (EDIT: as rici pointed out, the only allowance forp + 4
to be equal toq
is ifq
is “the start of a different array object that happens to immediately follow…”. Since NULL is not the address of any object, it follows thatp + 4 == NULL
is false).This blog post looks at this and other pointer comparisons in C.