Re: STL, memory allocation, and cleanup (gcc 3.0?)
On Mon, Nov 19, 2001 at 12:05:32PM +0100, Ulrich Eckhardt wrote:
> On Monday 19 November 2001 03:27, elf@florence.buici.com wrote:
> > I've written a C++ program to demonstrate behavior that I cannot
> > explain. It appears that the STL allocates memory that it never
> > frees. I'd like to believe that I'm missing something obvious, but
> > then it must not be obvious enough. Yes, I've run the debugger on it.
> > It looks to be a GCC bug, but I cannot be sure since I don't have an
> > explanation for the fact that a large block is allocated for the first
> > Map and not for the second, *and* there are no static members in the
> > Map template.
> >
> It is probably not a bug:
> the full template for most (all?) STL-containers is
> template<class Element, class Allocator=std::allocator<Element> >
>
> This allocator is a wrapper around the memory-management. I think there is a
> simple example for this in Stroustrup's Bible, as far as I remember, it went
My second edition doesn't appear to have a description of anything
STL. Are you using a later edition?
> like this:
> - the allocator has only static functions
> - the allocator is asked for a pointer to n contiguous elements. If it has
> some memory of proper size in its internal cache, it hands these to the
> container, else it calls eg malloc to get more.
> - when it is not needed anymore, the memory is given back to the allocator
> which adds the mem to its internal queue
> - when an operator new fails, the new_handler-function is called, first
> requesting the allocators to free their surplus memory, if that is not
> enough, the finalizing bad_allow is thrown.
This explains the behavior, large allocations created when the first object of a given type is created.
>
> I also remember seeing an alternate implementation on www.codeguru.com, if
> you're interested.
>
>
> > The program hooks new/delete and malloc/free, printing messages when
> > one is called. This all arose because I am using nearly identical
> > code in another application to prove that it is memory conservative.
> With your hooks, you're entering shallow waters here: there is no guarantee
> that all code is templatized, there can well be some part in a shared lib
> that then uses malloc without you seeing it.
>
> [snipped code]
> after adding a std:: here and there, this is the result with g++-3.0:
> uli@doommachine:uli$ ./a.out
> map_p
> malloc 12 -> 0x804c530
> free 0x804c530
> map_p
> malloc 12 -> 0x804c530
> free 0x804c530
> uli@doommachine:uli$
Interesting. The large blocks no longer appear. I'm going to
implement an alternative allocator to see if it makes this easier.
Thanks for your insightful reply.
Reply to: