[This is a follow-up to a previous question that got no responses. I'm trying to be more specific with my question in this post.]
I'm having a lot of trouble with a C Mex file that copies data from a large C structure to an mxArray structure that is returned to the Matlab workspace. The returned structure has the correct data, but if I clear the return variable, Matlab crashes.
I suspect that I should be creating a duplicate of the mxArray structure before returning it, because I set the field values by reference to data in temporary arrays whose memory space is likely being freed by the Mex function. When I try to use mxDuplicateArray(), however, Matlab crashes as soon as I call the Mex function. I suspect I'm running out of heap memory (???).
The structure in question is fairly large - 107 fields, several of which are float arrays with over 100 elements, and a few of which have over 1000 elements. Should I be allocating memory for this data and then freeing it? How do I do this?
I'm creating the mxArray structure with mxCreateStructMatrix(), but that function has no knowledge of the field types or sizes - those are defined only when I use mxSetField() to set the data for each field, passing a pointer to the mxArray in question.
Should I allocate memory for each field as I set its value? If so, when is it appropriate to free that memory? I can't do it until I've duplicated the structure to return to Matlab, can I?
I'm struggling quite a bit with this - in case that's not obvious - so any help will be much appreciated.