From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Destroy Array
Date: Tue, 23 Aug 2011 12:38:08 +0000 (UTC)
Organization: Universit&#228;t Bern
Lines: 31
Message-ID: <j306vg$md2$>
References: <j2tidu$2p4$> <j2tj0l$4qq$> <j2tpgo$s86$>
Reply-To: <HIDDEN>
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: 1314103088 22946 (23 Aug 2011 12:38:08 GMT)
NNTP-Posting-Date: Tue, 23 Aug 2011 12:38:08 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1490572
Xref: comp.soft-sys.matlab:740955

"James Tursa" wrote in message <j2tpgo$s86$>...
> "Stiphu" wrote in message <j2tj0l$4qq$>...
> > It used to work before (Matlab2010a, I use now 2011a). I made an example (which does the same thing like the code I posted above):
> > 
> > int myData[] = {1, 2, 3};
> > mxArray *prhsApp;
> > prhsApp = mxCreateDoubleMatrix(1, 3, mxREAL);
> > mxSetData(prhsApp, myData);
> > mexPutVariable("caller", "MEX_timeValues", prhsApp);
> > mxDestroyArray(prhsApp);
> > 
> > same result, Matlab crashes as soon as I call mxDestroyArray!
> Both of your examples crash because you are mixing native C memory (local automatic memory or heap allocated memory) into an mxArray variable. You can't do that because when mxDestroyArray is called you will mess up the MATLAB memory manager as it will try to free the memory behind the pointer you used in the mxSetData call. The proper way to do this is to first detach your C memory from the mxArray (NULLl out the data pointer), and then call mxDestroyArray on it. E.g.,
>  int myData[] = {1, 2, 3};
>  mxArray *prhsApp;
>  prhsApp = mxCreateDoubleMatrix(1, 3, mxREAL);
>  mxFree(mxGetData(prhsApp));  // Added line to avoid memory leak
>  mxSetData(prhsApp, myData);
>  mexPutVariable("caller", "MEX_timeValues", prhsApp);\
>  mxSetData(prhsApp, NULL);  // Added line to detach C native memory
>  mxDestroyArray(prhsApp);
> Your listed code also has a memory leak since you overwrite the mxArray data pointer without first freeing the memory that it points to. I have added another line to correct that.
> The reason you can get away with using the mixed memory mxArray in the mexPutVariable call is because this function creates a deep copy of the mxArray to put into the workspace, so no native C memory is pointed to in the actual variable that gets put in the workspace eve if there is native C memory in the original. Note that this would *not* be true if you tried to return this variable as one of the plhs[ ] array variables. If you were to try that then you would also likely crash MATLAB at some point downstream.
> James Tursa

Tnx James, this works perfectly!