MATLAB Answers


Memory leak with Mex

Asked by Sridutt Nayak on 11 Mar 2013

I am doing below in a loop with dims = [1024 768 256]

1. I want to read a set of block loaded by block_iter(1 to 16) into a RAM of Hardware. The memory call seems to display the memory leaking. Am I doing it wrong somewhere?

// Create memory for reading in data
        mxArray *B= mxCreateNumericArray(3,dims,mxUINT8_CLASS,mxREAL); 
        mxArray *in = mxCreateDoubleMatrix(1, 1, mxREAL);
// See Memory usage
          memcpy(mxGetPr(in), &block_iter, sizeof(double)*1*1);
// Read a block of 256 images of 1024*768. Even the temp variable is cleared in the dmd_feeder function
          ram_fill(d,B);  // As of now does nothing, its an empty void function and I would be replacing it to copy data to ram of hardware.
//Deallocate memory;

PS: The memory leak is around 192 MB each loop which is exactly the amount of data in array B

  1 Comment

Jan Simon
on 11 Mar 2013

What is "a loop with dims"? What is "block_iter(1 to 16)"? What does "memory exactly reply"? Do you mean the size of the largest available block or the sum of the free memory? What happens inside "data_feeder"? What is "d" in the call of ram_fill() and are you really sure, that this function does not matter? If so, why do you include it in the example?

Log in to comment.


1 Answer

Answer by James Tursa
on 11 Mar 2013
Edited by James Tursa
on 11 Mar 2013
 Accepted Answer

You are leaking memory behind the B mxArray. E.g.,

mxArray *B= mxCreateNumericArray(3,dims,mxUINT8_CLASS,mxREAL); 

The mxCreateNumericArray call allocates memory for the mxArray B. The subsequent mexCallMATLAB call allocates a brand new mxArray B. The call itself overwrites the value of B with a new value. The currently existing B value from your previous mxCreateNumericArray call becomes lost and thus you leak the memory behind it (at least temporarily until the mex routine exits back to the calling function). You need to get rid of your mxCreateNumericArray call since mexCallMATLAB will allocate memory for the B result itself.

  1 Comment

Jan Simon
on 29 Apr 2013

I have accpeted this answer.

Log in to comment.

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!