haskell-numerics / hmatrix

Linear algebra and numerical computation
381 stars 104 forks source link

Memory leaks in C code #326

Closed HuwCampbell closed 4 years ago

HuwCampbell commented 4 years ago

Looking at the C code, a very common pattern is this:

doublecomplex * workv = (doublecomplex*)malloc(n*sizeof(doublecomplex));
CHECK(!workv,MEM);
do_stuff(&work, &res);
CHECK(res,res);
free(workv);
OK

where CHECK and OK are macros which call return. There's an issue here in that if the calls to CHECK fail, none of the memory allocated will be freed (until the program exits completely).

HuwCampbell commented 4 years ago

Fixing this is pretty mechanical. I've fixed up a few by creating a macro UNWIND, which sets a return variable and jumps to a label where we will call free.

    UNWIND(!work,MEM,done)
    do_stuff (&work, &res);
    UNWIND(res,res,cleanup)

cleanup:
    free(work);
done:
    return ret;
HuwCampbell commented 4 years ago

This is also effecting calls to solvers, so singular matrices under the linear solve family are leaking memory.

idontgetoutmuch commented 4 years ago

Fixed by https://github.com/haskell-numerics/hmatrix/pull/327