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

akaz nemo at utopia.com
Fri Jul 6 20:02:05 PDT 2012


On Friday, 6 July 2012 at 21:10:56 UTC, Simon wrote:
> 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 пишет:
>
> 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.

OTOH, the other case that's given on the original page is this 
one:

	int* p = new int;
	int x = reinterpret_cast<int>(p);	// non-portable
	p=0;
	// ... collector may run here ...
	p = reinterpret_cast<int*>(x);
	*p = 10;	// can we be sure that the int is still there?

So, the pointer could sometimes simply disappear temporarily, 
without becoming invalid (well, p==NULL is somewhat invalid, bt 
it could have been p=&q). Just some allocated memory is no longer 
referenced for the time being and this could trigger the GC 
without protection (except disabling GC for the entire 
application).

Won't some functions doing just what addRange() and removeRange() 
do solve that kind of problem (if necessary)? That means, 
forbidding the GC to scan some memory area for some time?


More information about the Digitalmars-d-learn mailing list