I apologize if this question is a duplicate - I have been looking for some time, but it is possible that my Google-fu is simply not up to the tobacco.
I am changing 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 trick is that a C ++ program can throw an exception halfway through execution, as a result of which the allocated memory will never be freed.
As an example (far-fetched):
char *allocate_lots() { char *mem = (char *)malloc(1024); return mem; } 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);
My question is: how do I deal with this? My first idea was to wrap it all in a try / catch block, and in catch just check and free the memory and throw the exception again, but that seems rude and clumsy to me (and won't work if I really want to catch an exception). Is there a better way to do this?
EDIT: I probably should have mentioned that we used g ++ 4.2.2 from 2007, before std :: unique_ptr was introduced. Chalk it to corporate inertia.
source share