5 ms·
> Wrap malloc in a function that push malloc'ed pointer on a global stack, insert NULL at the point where a try happens. When you throw an exception, simply fre
by rcfox 15y ago
> Wrap malloc in a function that push malloc'ed pointer on a global stack, insert NULL at the point where a try happens. When you throw an exception, simply free everything on the stack until the previous NULL. Problem solved.
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.
- daeken 15y ago> 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.
- rcfox 15y agoThat makes more sense. I assumed he meant to free memory before throwing the exception.
- sausagefeet 15y agoSo every function now needs a try/catch? Doesn't this kind of defeat the purpose?
- daeken 15y agoEvery call to a function that can throw an exception should have a try/catch block, so that things can be properly cleaned up. Global exception handlers are seldom useful outside of reporting the existence of an error for future usage.
- sausagefeet 15y agoBut every function can potentially throw an exception...
- rwallace 15y agoIn that case, wouldn't it be simpler to explicitly check for error return on every call to such a function, and eliminate the need for an exception mechanism?
- norswap 15y agoKind of defeat the point of exceptions in the first place. It becomes more like an "enhance error return value" thing. 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.
- norswap 15y agoGood point, but then again, control over memory is kind of the C killer feature, so you should know how memory flows around in your program. 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.