Pete Becker
11/15/2008 5:37:00 PM
On 2008-11-15 12:21:06 -0500, Juha Nieminen <nospam@thanks.invalid> said:
>
> I have absolutely no experience in third-party garbage collectors for
> C++. What I have always wondered, though, is how those can handle a
> situation like:
>
> int* foo()
> {
> int* table = new int[100];
> return table+40;
> }
>
> The pointer to the beginning of the allocated array dies when foo()
> terminates, but a pointer to one of its elements lives beyond the scope
> of foo(). This pointer may be used in the calling code. A garbage
> collector would have to:
>
> 1) Know that there's still a live pointer pointing to (an element
> inside) the array, and thus it cannot destroy it yet.
>
> 2) Know to delete the array properly (ie. from the original pointer
> pointing to the beginning of the array, rather than the one which lived
> longer than that) when that returned pointer dies and the GC runs.
>
> I suppose they have figured out these problems. I'm just wondering how.
It's just a bit of bookkeeping. When the array is allocated the
collector makes notes about the size of the allocated block and where
it begins. The returned pointer points into the allocated block, so the
block is still live.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)