How to free memory after an exception is thrown in C ++?


I apologize if this question is a duplicate - I searched for a while, but it's possible that my Google-fu just isn't up to snuff.

I am modifying a C++ program that calls into a C library. The C library allocates a bunch of memory (using malloc()), and the C++ program uses it and then frees it. The catch is that the C++ program can throw an exception midway through execution, causing the allocated memory to never be freed.

As a (rather contrived) example:

/* old_library.c */
char *allocate_lots() {
    char *mem = (char *)malloc(1024);
    return mem;

/* my_prog.cpp */
void my_class::my_func () {
    char *mem = allocate_lots();
    bool problem = use(mem);
    if (problem)
        throw my_exception("Oh noes! This will be caught higher up");
    free(mem);  // Never gets called if problem is true

My question is: how ought I to deal with this? My first idea was to wrap the whole thing in a try/catch block, and in the catch just check and free the memory and re-throw the exception, but this seems graceless and clunky to me (and wouldn't work well if I want to actually catch an exception). Is there a better way to do it?

EDIT: I probably should have mentioned that we're using g++ 4.2.2, from back in 2007 before std::unique_ptr was introduced. Chalk it up to corporate inertia.

Use std::unique_ptr with a custom deleter that calls free:

class free_mem {
    void operator()(char *mem) { free(mem); }

void my_class::my_func() {
    std::unique_ptr<char, free_mem> mem = allocate_lots();