On Sat, 2021-06-19 at 16:23 +0100, Dmitrii Pasechnik wrote:
> > I don't think I understand.
>
> p[] occupies a continuous memory area, starting from p[0], but p[-1]
> is not guaranteed by the standard to be accessible for you (well,
> unless you control the memory layout by placing p in a struct, not as
> the 1st member, but then why would you need p[-1] in the 1st place?)
>
> What's unclear about it?
The problem is that your initial premise is not correct. p here is not
an array, it's a pointer. If we had declared it like this:
char p[10]
then p[-1] would be problematic. But, we don't declare that.
We declare it like this:
char *p
so p is a pointer. It points to some memory, and it can (and does)
move both forward AND backward through that memory, via p+X and p-X.
That's perfectly legitimate and not illegal or a hack in any way.
I guess the compiler believes that it's possible that p might point to
the very start of some legitimate memory, and if that were true then
p[-1] (or, equivalently, *(p-1)) would be undefined behavior.
But, as human programmers we can examine this code and understand that
actually, it's never possible for p to point to the first character of
the array: we know that eval_strings->idx is never 0, so we know that p
will always be incremented past the beginning of the memory buffer:
p = value = alloca (len);
for (i = 0; i < eval_strings->idx; ++i)
{
...
*(p++) = ' ';
}
p[-1] = '\0';