Archive for July, 2004

GCC 3.3.2 and STL

Tuesday, July 6th, 2004

Whew! I've gotten a few very difficult memory issues taken care of in an app I'm working on. Interestingly enough, the points boil down to a few things:

  • don't use mutexs in destructors if possible - this one got me on a few occasions
  • delete pointers in maps obviously - and don't try to set the value part of the map to NULL after the delete. Use a while loop on the map's empty() method to get all the front() elements in the map.

Before I made sure of these few things I had lots of unusual and hard to pin down memory problems. Now that I've implemented these in all the classes of my app, things are running much smoother now.

You'd think that the following is a valid way to build a destructor:

    std::map<int, char*>	mMap;

    Egg::~Egg()
    {
        std::map<int, char*>::iterator     i;
        for (i = mMap.begin(); i != mMap.end(); ++i) {
            if (i->second != NULL) {
                delete i->second;
                i->second = NULL;
            }
        }
        mMap.clear();
    }

Oh, but you'd be wrong. The problem seems to be in the setting of the NULL into the value part of the map after the (char*) has been deleted. The way to get this to properly run in GCC 3.3.2 on Solaris 8 is to frame the destructor a little differently:

    std::map<int, char*>	mMap;

    Egg::~Egg()
    {
        std::map<int, char*>::iterator     i;
        while (!mMap.empty()) {
            i = mMap.front();
            if (i->second != NULL) {
                delete i->second;
            }
            mMap.erase(i);
        }
    }

Guess there's a good way and a not so good way to do STL things in GCC.