c++cexceptionalloca

Does alloca() return memory if an exception is thrown?


I'm maintaining a legacy C++ application that seems to have a slow memory leak. I've managed to "fix" the memory leak by ensuring that the current configuration no longer throws any exceptions and I can also trigger the leak and scale it by configuring it to result in many exceptions.

All the memory that is allocated is done using alloca() rather than malloc(). The explanation I've been given for this is that it's because alloca() works like the java garbage collector and automatically frees the memory when it exits the context.

Due to the leak being so clearly bound to the exceptions being thrown I have the theory that alloca() is failing to free the memory when exceptions are thrown.

Is this at all plausible? It strikes me as a major defect in alloca() if true but when I google alloca() it seems to generally be a problem.

I'd appreciate the insight on any experts.


Solution

  • It is likely that the problem is due to a level of indirection.

    The literal question is "does alloca return memory if an exception is thrown?". And the answer to that is; It returns only the memory that was directly allocated. No destructors are run, and any owning pointer inside the alloca-allocated memory is leaked.