用于平衡alloc/free的C Pattern/Idiom

Tra*_*ggs 2 c memory-management allocation bare-metal

我有一堆遵循简单模式的代码:

Thing *myThing = newThing(); // allocation happens here
...
thingFuncA(myThing);
... and other computations ...
thingFuncB(myThing);
...
thingFree(myThing);
return result;
Run Code Online (Sandbox Code Playgroud)

应用程序的thingFuncX()变化与其他计算的变化一样,但最终总是免费的模式始终是相同的.

我需要在这里使用原始C(低,而不是C++,它的花式范围分配),我在半限制处理器上运行裸机.

有没有办法(ab)使用CPreprocessor来捕获这种常见模式.我想要使​​用一个成语,这样我就可以放心,不会忘记自由.我想我也许可以用一个宏做一些事情while { } do ()(一个例子的答案在这种情况下会有所帮助).或者也许还有一些其他聪明的C技巧我忽略了?

Bla*_*iev 5

GCC提供的cleanup属性基本上允许您在C中使用基于范围的析构函数:

void function(void) {
    Thing *myThing __attribute__((cleanup(callback))) = newThing();
    ...
    thingFuncA(myThing);
    thingFuncB(myThing);
}

void callback(Thing **thing) {
    thingFree(*thing);
}
Run Code Online (Sandbox Code Playgroud)