Smart pointers/safe memory management for C?

后端 未结 9 573
闹比i
闹比i 2020-12-07 17:31

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 memo

9条回答
  •  庸人自扰
    2020-12-07 18:09

    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.

提交回复
热议问题