haskell-numerics / hmatrix

Linear algebra and numerical computation
381 stars 104 forks source link

Fix memory leaks in C code #327

Closed HuwCampbell closed 4 years ago

HuwCampbell commented 4 years ago

This PR may need some eyes over it, there's a lot of code, and although the tests pass there's a chance I've got a jump wrong.

Almost all the malloc calls in lapack-aux.c seem to be vulnerable to memory leaks; but the ones which don't succeed with all valid matrices seem very problematic.

Currently, a call to linearSolve will fail for a singular matrix as it should, but it won't free the memory it has allocated in order to know it should fail. That's really bad.


Use an unwinding method to free memory in the event of failure.

There's three idioms at use here.

CHECK; MARK/CONVERGED; UNWIND.

CHECK is as it was, it exits the function immediately with a code.

MARK and CONVERGED set the variable ret to a suitable exit code for the function, but don't return or jump.

UNWIND sets ret and jumps to the point where it will free all the memory that has been allocated so far.


Fixes: #326

HuwCampbell commented 4 years ago

This PR was on top of the segfault one. So it's not on master just yet.

HuwCampbell commented 4 years ago

Sorry about that. My plan was to merge the other PR first, then rebase, then repoint PR on to master.

idontgetoutmuch commented 4 years ago

No need to apologise. I should have looked more carefully at the target.