Garbage Collection Pitfall in C++ but not in D?

David Nadlinger see at klickverbot.at
Sat Jul 7 04:05:43 PDT 2012


On Saturday, 7 July 2012 at 03:02:07 UTC, akaz wrote:
> On Friday, 6 July 2012 at 21:10:56 UTC, Simon wrote:
>> On 06/07/2012 16:39, Alex Rønne Petersen wrote:
>> Never mind what D says, even in C/C++ just doing the p += 10 
>> is invalid.
>>
>> Creating a pointer that points at invalid memory is just as 
>> wrong as dereferencing it would be.
>
> Actually, p+10 could still be valid memory.

Not if p+10 was not allocated as part of the same block as p was 
(i.e. if p is the result of »new int«, it is always illegal). 
It might »physically« work with the common C/D implementations 
if another chunk of your memory is at that address, just as 
*(cast(int*)0xdeadbeef) could potentially work, but it is 
undefined behavior by the rules of the language. If the compiler 
can prove that when allocating the memory p points at, p + 10 was 
not allocated as well, it would even be free to directly replace 
a read from that pointer with an undefined value.

David


More information about the Digitalmars-d-learn mailing list