0

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);
}
glglgl
  • 89,107
  • 13
  • 149
  • 217
  • I am not sure, but I think that if there is not enough memory, matlab goes out of your mex file directly. In that case, maybe you can still catch an exception or something... Anyway, you can type `edit([matlabroot '/extern/examples/refbook/matrixDivideComplex.c']);` to see a mex file coded by Mathworks, they do nothing special before calling `mxDestroyArray`. – Oli Feb 08 '12 at 20:03
  • @Oli In the case of a mex file, you are right. But there is as well the other direction - calling MATLAB from an external program - which is currently my issue. And there you can get a NULL. – glglgl Feb 08 '12 at 23:49

2 Answers2

3

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

tim
  • 9,896
  • 20
  • 81
  • 137
  • For free(), I don't need the check - which is quite convenient. For the check: The problem is, if it works now, there is no guarantee that it works in later versions as well. But nevertheless, I'll check tomorrow. – glglgl Feb 08 '12 at 23:50
  • I just tested and the program didn't crash. So I suppose that it works. Nevertheless, I'll keep it in for now... – glglgl Feb 09 '12 at 09:42
2

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.

siliconwafer
  • 732
  • 4
  • 9
  • I am thinking about the other direction: calling MATLAB from outside. And here, nothing will be destroyed. I would like to try to completely avoid memory leaks as my program sometimes needs to run for several days. – glglgl Feb 08 '12 at 23:51