[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

STL, memory allocation, and cleanup (gcc 3.0?)



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.

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.

Questions include:

  1) Is there a gcc 3.0 machine I can use to run this test?
  2) Is this something known about STL?

/* freetest.cc

   written by Marc Singer
   18 Nov 2001

*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define free _free
#define malloc _malloc
#define realloc _realloc

#include <list>
#include <stack>
#include <map>

#undef free
#undef malloc
#undef realloc

typedef map<char*, char*> Map;
typedef pair<char*, char*> Pair;

class Wrap {
public:
  //  list<char*> l;
  Map m;
};

class Cover {
public:
  Wrap w;
};

void* _malloc (size_t cb)
{
  void* pv = malloc (cb);
  printf ("malloc %d -> 0x%x\n", cb, pv);
  return pv;
}

void _free (void* pv)
{
  printf ("free 0x%x\n", pv);
  free (pv);
}

void* operator new (size_t cb)
{
  return _malloc (cb);
}

void operator delete (void* pv)
{
  _free (pv);
}

void* operator new [] (size_t cb)
{
  return _malloc (cb);
}

void operator delete [] (void* pv)
{
  _free (pv);
}

void operator delete [] (void* pv, size_t cb)
{
  _free (pv);
}

void test_list (void)
{
  list<char*> l;
}

void test_list_p (void)
{
  list<char*>* pl = new list<char*>;
  delete pl;
}

void test_map (void)
{
  Map m;
  m.insert (Pair ("one", "two"));
}

void test_map_p (void)
{
  Map* pm = new Map;
  pm->insert (Pair ("one", "two"));
  delete pm;
}

void test_wrap (void)
{
  Wrap w;
}

void test_wrap_p (void)
{
  Wrap* pw = new Wrap;
  delete pw;
}

void test_cover_p (void)
{
  Cover* pc = new Cover;
  delete pc;
}


int main (int argc, char** argv)
{
  //  printf ("list\n");		test_list ();
  //  printf ("map\n");		test_map ();
  printf ("map_p\n");		test_map_p ();
  printf ("map_p\n");		test_map_p ();
  //  printf ("list_p\n");		test_list_p ();
  //  printf ("wrap\n");		test_wrap ();
  //  printf ("wrap_p\n");		test_wrap_p ();
  //  printf ("cover_p\n");		test_cover_p ();
  exit (0);
}
/*
 Local Variables: ***
 compile-command: "gcc -o freetest freetest.cc" ***
 End: *** */




Reply to: