Smart pointers/safe memory management for C?

2019-01-16 16:14发布

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.

8条回答
一纸荒年 Trace。
2楼-- · 2019-01-16 16:56

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.

查看更多
相关推荐>>
3楼-- · 2019-01-16 16:59

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.

查看更多
登录 后发表回答