From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: mexCallMATLAB crashes in loops?
Date: Wed, 2 Jan 2013 23:03:10 +0000 (UTC)
Organization: Boeing Co
Lines: 10
Message-ID: <kc2ebe$mkl$>
References: <kbt4p3$n00$> <kbu49s$3g8$> <kbv5ko$it4$> <kc27ra$sau$> <kc2cor$he8$>
Reply-To: <HIDDEN>
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: 1357167790 23189 (2 Jan 2013 23:03:10 GMT)
NNTP-Posting-Date: Wed, 2 Jan 2013 23:03:10 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 756104
Xref: comp.soft-sys.matlab:785811

"Yi " <> wrote in message <kc2cor$he8$>...
> So I cleaned the mout[0] in each loop and cleaned the incall[0] in the end. The code works for now yet I still have a question: 
> Is it necessary to clean the mout[0] in the loop?  Can I clean it up in the end of the code (with incall[0])?

Each mout[0] that gets created inside your loop is tagged as a temporary variable that gets put on the garbage collection list. Every time you call mexCallMATLAB to generate another mout[0] you lose the pointer to the old mout[0] variable (i.e., the current mout[0] value gets wiped out and overwritten by the new value) and thus you have created a temporary memory leak. However, once your mex function returns control back to the calling function (i.e., MATLAB in this case) all of the variables on the garbage collection list get automatically destroyed by MATLAB, so your memory leaks get fixed. This is why the memory leaks you created inside the loop are temporary. That being said, it is good programming practice not to generate memory leaks like this in the first place, so I would advise destroying the mout[0] variables at the end of each loop iteration (and concurrently get rid of the 
one mxDestroyArray(mout[0]) at the end). 

James Tursa