views:

774

answers:

4

Hi,

I, and I think many others, have had great success using smart pointers to wrap up unsafe memory operations in C++, using things like RAII, et cetera. However, wrapping memory management is easier to implement when you have destructors, classes, operator overloading, et cetera.

For someone writing in raw C99, where could you point (no pun intended) to help with safe memory management?

Thanks.

+6  A: 

It's difficult to handle smart pointers in raw C, since you don't have the language syntax to back up the usage. Most of the attempts I've seen don't really work, since you don't have the advantages of destructors running when objects leave scope, which is really what makes smart pointers work.

If you're really worried about this, you might want to consider just directly using a garbage collector, and bypassing the smart pointer requirement altogether.

Reed Copsey
+3  A: 

Static code analysis tools like splint or Gimpel PC-Lint may help here -- you can even make these moderately "preventative" by wiring them into your automatic "continuous-integration" style build server. (You do have one of those, right? :grin:)

There are other (some more expensive) variants on this theme too...

leander
+1 Good call on the static code checking tools.
Reed Copsey
+1  A: 

If you are coding in Win32 you might be able to use structured exception handling to accomplish something similar. You could do something like this:

foo() {
    myType pFoo = 0;
    __try
    {
        pFoo = malloc(sizeof myType);
        // do some stuff
    }
    __finally
    {
        free pFoo;
    }
}

While not quite as easy as RAII, you can collect all of your cleanup code in one place and guarantee that it is executed.

Steve Rowe
+2  A: 

Another approach that you might want to consider is the pooled memory approach that Apache uses. This works exceptionally well if you have dynamic memory usage that is associated with a request or other short-lived object. You can create a pool in your request structure and make sure that you always allocate memory from the pool and then free the pool when you are done processing the request. It doesn't sound nearly as powerful as it is once you have used it a little. It is almost as nice as RAII.

D.Shawley