Garbage Collection Pitfall in C++ but not in D?
Simon
s.d.hammett at gmail.com
Fri Jul 6 14:10:57 PDT 2012
On 06/07/2012 16:39, Alex Rønne Petersen wrote:
> On 06-07-2012 16:07, Denis Shelomovskij wrote:
>> 06.07.2012 17:43, akaz пишет:
>>> Hi,
>>>
>>> Reading about the C++11, I stumbled upon this:
>>>
>>> http://www2.research.att.com/~bs/C++0xFAQ.html#gc-abi
>>>
>>> Specifically (quote):
>>>
>>> int* p = new int;
>>> p+=10;
>>> // ... collector may run here ...
>>> p-=10;
>>> *p = 10; // can we be sure that the int is still there?
>>>
>>> How does the D garbage collector solves (answers) that?
>>>
>>> Thank you.
>>
>> If you are interested in D read this first:
>> http://dlang.org/garbage.html
>>
>> You can find there e.g.:
>> > Do not add or subtract an offset to a pointer such that the result
>> points outside of the bounds of the garbage collected object originally
>> allocated.
>>
>> So `p+=10;` is already "undefined behavior".
>>
>
> I'll just add: Handling this case is basically impossible to do sanely.
> You can't really know what some pointer off the bounds of a managed
> memory region is based on. It could literally be based on any memory
> region in the entire program. You could do heuristics of course, but . . .
>
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. The possible crash on the dereference of the
pointer is just the symptom of the under lying bug.
With visual studio & their implementation of the std containers, in a
debug build if you increment/decrement or otherwise create an iterator
that's outside the allowable bounds of the container you get a runtime
assertion failure.
It's a very handy feature and uncovered a load of bugs when we upgraded
to VS 2008.
--
My enormous talent is exceeded only by my outrageous laziness.
http://www.ssTk.co.uk
More information about the Digitalmars-d-learn
mailing list