Using the C Math Library | ![]() ![]() |
Avoiding Memory Leaks in Your Functions
Follow these recommendations to avoid the memory leaks.
mlfAssign()
) or without embedding the call as an argument to a library function.
Memory leak:
mlfSin(X);
The array returned by mlfSin()
is not bound to a variable and never freed.
Memory leak:
void func(mxArray *y) { mxArray *x; mlfEnterNewContext(0,1,y); mlfAssign(&x, mlfSin(y)); mlfRestorePreviousContext(0,1,y); }
You must pair each mxArray*
declaration with a call to mxDestroyArray()
.
Unexpected termination of your program:
x
is a temporary array. If x
is subsequently passed as an input argument to
a function, that function will delete x.
Any subsequent reference to x
will
cause your program to crash.
x = mlfSin(y); /* x is temporary. */ a = mlfPlus(x, mlfScalar(1)); /* x is deleted. */ b = mlfPlus(a, x); /* Program crashes. */
![]() | Automated Memory Management | Using Automated Memory Management | ![]() |