Travis Griggs
Travis Griggs

Reputation: 22252

C Pattern/Idiom for balancing alloc/free

I have a bunch of code that follows a simple pattern:

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

The application of thingFuncX() varies as does the other computations, but the pattern that it is always free'ed at the end is always the same.

I need to use raw C here (iow, not C++ with it's fancy scoping allocations), I'm running bare metal on a semi-limited processor.

Is there a way to (ab)use the CPreprocessor to capture this common pattern. I'd like to have an idiom I use so I can have confidence that a free won't be forgotten. I think I could maybe do something with a macro and a while { } do () (an answer that was an example would help in that case). Or maybe there's some other clever C trick I'm overlooking?

Upvotes: 2

Views: 219

Answers (1)

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43538

GCC provides the cleanup attribute which essentially allows you to have scope-based destructors in C:

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

void callback(Thing **thing) {
    thingFree(*thing);
}

Upvotes: 5

Related Questions