Smart pointers/safe memory management for C?

Viewed 30599

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.

9 Answers

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.

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.

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...

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.

Ok, so here are your options. Ideally, you combine them to get better result. In case of C, paranoia is fine.

Compile-time:

  1. Use the cleanup variable attribute in GCC. You have to stick to GCC after that. This limits portability of your code because you can only target platforms for which GCC exists.
  2. Use SEH (structured exception handling) on Windows. This limits your portability even further because your have to use the Microsoft compiler. If your target is exclusively Windows, then it will work for you.
  3. Use the static code analysis tool revealing potential memory leaks. Doesn't work perfectly, but can help find trivial leaks. Doesn't affect your portability.

Runtime:

  1. Use the debug memory allocation library which replaces malloc/free with its own implementations and tracks memory usage. This way you can see blocks that were allocated but never released. I had success with the one for Solaris (will try to remember its name).
  2. Use a garbage collector. I had a positive experience with Hans-Boehm GC while fixing a very leaky C application that I didn't have the source code for. I could see how memory consumption was climbing, then it plummeted when the GC did its work.
Related