|
From: Olly B. <ol...@su...> - 2003-09-30 08:15:29
|
On Mon, Sep 29, 2003 at 05:33:50PM -0700, Steve G wrote:
> >For what it's worth, going one past the end is a special case
> >in the C standard and is allowed
>
> What if the loop increments by 2?
Then if the pointer ends up more than one past the end of the block, the
program will invoke undefined behaviour according to the C standard.
If this worries you, allocate the block with the size rounded up to an
even number...
Note that undefined behaviour can be anything, including what you
expect (i.e. that it works as if the array were larger). That it works
on a particular compiler/platform doesn't mean it's actually
well-defined ISO C.
> The pointer can point 100 past the end legally. It just can't
> read or write to memory. :)
If it points 100 past the end, all bets are off. On a typical modern
machine with a flat memory space, it'll probably work as you hope.
But it's not maximally portable - for example, on a DOS machine in (say)
small memory model, it's likely to fail if you try it with a block of
memory ending less than 100 bytes from the end of the segment.
I can't easily check but I suspect the pointer would wrap and compare
less than the end value, so the loop won't terminate correctly, but
instead continue over into the start of the segment.
Cheers,
Olly
|