Question

I use MATLAB's mxDestroyArray() function and wonder how to do proper error handling.

If I called mxCreate*Array() or similiar, I get a valid pointer on success and NULL on failure, i. e. if memory is full.

If I create several arrays in this way and at least one fails, I would like to free all what I don't need any longer.

Here I am wondering: Do I need to explicitly check every value?

if (error) {
    if (a) mxDestroyArray(a);
    if (b) mxDestroyArray(b);
    if (c) mxDestroyArray(c);
}

or can I just omit the checks?

if (error) {
    mxDestroyArray(a);
    mxDestroyArray(b);
    mxDestroyArray(c);
}
Was it helpful?

Solution

Simply try it and see if matlab crashes. I think you need the check as you also do in plain C as null isn't referencing a valid memory address

OTHER TIPS

I don't think this is necessary and I don't bother to clean-up such memory for a few reasons:

  1. If a call to an mxCreate* function fails, it is most likely because you're out of memory. With some versions of the MEX API this will result in a segmentation violation and you won't have an opportunity to perform clean-up anyways.

  2. MATLAB will automatically destroy any arrays that are not returned from the MEX Function in plhs[] when the MEX Function terminates or when there is a call to mxErr.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top