Ben Pope wrote in
news:1122540209.1629051a7bcb71987b0faeff0f5fb4f8@t eranews in
comp.lang.c++:
[color=blue][color=green][color=darkred]
>>>>> int* p = a;
>>>>> ++p; // OK, points to the second element (indexed 1).
>>>>> ++p; // OK, points to one-past-the-end value.
>>>>> ++p; // What happens here? Is p a valid pointer? And what if
>>>>> the array
>>>>>was allocated dynamically?[/color][/color][/color]
[color=blue][color=green][color=darkred]
>>>Surely he only has undefined behaviour if he actually dereferences
>>>it?[/color]
>>
>>
>> If it isn't undefined, then surely it must be defined, so what does
>> it do ?[/color]
>
> I guessed the pointer was equal to a + 3*sizeof(int), regardless of
> what is or isn't there, but presumably it doesn't, which is why
> dereferencing it is bad.[/color]
There are implementations where you have ((p + n) - n) == p, for
any non-void pointer p and any int n. There are other implementations
where a pointer (in a register) that doesn't actually point to valid
memory causes some kind of fault.
On such an implementaion the call (new int[10]) will need to allocate
11 int's just to make sure the one-passed-the-end rule is valid.
All implemetations need to avoid allocating the top of memory as
the last element of an array, as otherwise the requirment:
some_type array[N];
assert( (array + N) > (array + 0) );
i.e. the one-passed-the-end rule, will fail.
The point I'm trying to make is that undefined behaviour has
a plus side, the language is effeciently portable to a greater
number of platforms becuase of it.
For example, if the language allowed arbitary additions and
subtractions from pointers then platforms with checked pointer
registers would need to store and do all there arithmatic in
non-pointer registers, and then only load these values into the
pointer registers when dereferencing. This is against the
"Don't pay for what you don't use", "Spirit of C" that C++ inherited.
[color=blue]
> presumably thats why:
> std::vector<int> v;
> std::vector<int>::iterator i = v.begin();[/color]
Undefined Behaviour starts here:
[color=blue]
> i--;[/color]
All bets are now off.
[color=blue]
> i++;
>
> Isn't guaranteed to point to *v.begin()?[/color]
Its worse than that, there is nolonger anything gauranteed.
undefined-behaviour,-it-really-does-what-it-says-on-the-tin-ly yr's Rob.
--
http://www.victim-prime.dsl.pipex.com/