Better yet, simply free memory at the exception throw site, if possible.
This frees everything, which isn't what you want. What if you've passed your pointer off to somewhere else where it's still in use?
> Better yet, simply free memory at the exception throw site, if possible.
Most of the time, your exceptions are coming from low levels, like IO libraries, that don't know anything about the memory that you've allocated.
Yeah, but that's why you put exception handlers around anything that you expect to throw an exception, IO being a big one. Dealing with memory cleanup is definitely something that should be handled in the function allocating the memory.
The thing about an exception is that you can't do about it in a number of scopes. When you encounter the exception you just just jump to the scope where you can do something about it.
If you use libraries that use internal malloc'ed memory, etc, you have to clean at the exception call site by calling the library cleanup function.
No, it's pretty simple. Postgres does it with something called regions: your code essentially becomes transaction-based, where resources that need cleanup are put into a region associated with a try block, and all remaining resources at the end of the block's (successful or failed) execution are freed. It requires slightly more work than in C++, obviously, because you're not using C++.
This third one makes using longjmp for exceptions almost untenable in real life code. You can make it easier to track and free memory correctly by using a pool allocator for the whole program, which may or may not be realistic, but I once wrote a webserver this way (from scratch, hey it was the 90s).