Got Questions? Get Answers.
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

Thread Subject:
Memory leak in Matlab 2012a?

Subject: Memory leak in Matlab 2012a?

From: Jesper Holm

Date: 11 Oct, 2012 07:38:09

Message: 1 of 8

Hi,

I've been struggling with a MCR executable that runs out of memory during 2-3 weeks of continuous running (we are using MCR for realtime continuous measurements and analysis).

After hours and hours of debugging I was able to get rid of the memory leak by removing annotations from my figures. I've submitted a service request to MathWorks but they are not able to reproduce my problem (the service request is still open so all hope is not lost).

The fact that Mathworks is unable to reproduce my findings troubles me. Are my memory problems related to "external" components (i.e. java installation etc)?

I'm therefore hoping that some of you would try to run the script below and let me know what you see. The Niters variable determines the number of loops. It's currently set to 1000 but feel free to modify it. The example is based on suggestions from MathWorks and Niters have to be large enough to see a clear trend.

The script uses the memory() function which is only available in later Matlab versions.
On Matlab 2012a (which is what we use currently) I see a 20Mb increase in used matlab memory after the test run. This memory is never released - you have to quit Matlab before getting it back. I've also run a few tests on 2012b. Here, the problem is not so large but I still see an increase in used memory (3-5Mb).

Anyway.. The script is presented below. Sorry if the formatting gets screwed up. If I comment the two annotation lines the problem goes away on my setup.

---------------------

function memleak3()

    clear all;
    close all;
    clc;

    t = clock;
    Niters = 1000;
    memused = zeros(1,Niters);
    for iter = 1:Niters
        fprintf('Iteration %d of %d\n',iter,Niters);
        
        runLeakingCode();

        info = memory;
        memused(iter) = info.MemUsedMATLAB;
        close all;
        clc;
        clearvars -except Niters memused iter t
    end
    
    plot(1:Niters,memused,'r-o');
    grid on;
    fprintf('Max = %d, Min = %d, Diff = %d\n',max(memused),min(memused),max(memused)-min(memused));
    
    t = fix(etime(clock,t));
    fprintf('Elapsed time = %d seconds..\n',t);
end

function runLeakingCode()
    x = 0:0.01:7;
    y = sin(x);
    z = cos(x);

    figStringA = 'Figure A';
    figStringB = 'Figure B';
    
    hFigure2 = figure(200);
    clf;
    set(hFigure2,'name',figStringA);
    annotation('textbox',[0 0.00 1 0.05],'VerticalAlignment','bottom','FitHeightToText','off','LineStyle','none','Margin',2,'String',figStringA,'FontSize',7);
    annotation('textbox',[0 0.95 1 0.05],'VerticalAlignment','top','FitHeightToText','off','LineStyle','none','Margin',2,'String',figStringB,'FontSize',7);
    subplot(2,1,1);
    plot(x,y);
    grid on;
    subplot(2,1,2);
    plot(x,z);
    grid on;
end

Subject: Memory leak in Matlab 2012a?

From: Jesper Holm

Date: 11 Oct, 2012 07:43:09

Message: 2 of 8

I forgot to add that I'm running on Windows 7 professional SP1 and Windows Server 2008 R2 enterprise

Regards,
Jesper

Subject: Memory leak in Matlab 2012a?

From: Yair Altman

Date: 11 Oct, 2012 10:39:08

Message: 3 of 8

"Jesper Holm" wrote in message <k55t11$qm7$1@newscl01ah.mathworks.com>...
> Hi,
>
> I've been struggling with a MCR executable that runs out of memory during 2-3 weeks of continuous running (we are using MCR for realtime continuous measurements and analysis).
>
> After hours and hours of debugging I was able to get rid of the memory leak by removing annotations from my figures. I've submitted a service request to MathWorks but they are not able to reproduce my problem (the service request is still open so all hope is not lost).
>
> The fact that Mathworks is unable to reproduce my findings troubles me. Are my memory problems related to "external" components (i.e. java installation etc)?
>
> I'm therefore hoping that some of you would try to run the script below and let me know what you see. The Niters variable determines the number of loops. It's currently set to 1000 but feel free to modify it. The example is based on suggestions from MathWorks and Niters have to be large enough to see a clear trend.
>
> The script uses the memory() function which is only available in later Matlab versions.
> On Matlab 2012a (which is what we use currently) I see a 20Mb increase in used matlab memory after the test run. This memory is never released - you have to quit Matlab before getting it back. I've also run a few tests on 2012b. Here, the problem is not so large but I still see an increase in used memory (3-5Mb).
>
> Anyway.. The script is presented below. Sorry if the formatting gets screwed up. If I comment the two annotation lines the problem goes away on my setup.
>
> ---------------------
>
> function memleak3()
>
> clear all;
> close all;
> clc;
>
> t = clock;
> Niters = 1000;
> memused = zeros(1,Niters);
> for iter = 1:Niters
> fprintf('Iteration %d of %d\n',iter,Niters);
>
> runLeakingCode();
>
> info = memory;
> memused(iter) = info.MemUsedMATLAB;
> close all;
> clc;
> clearvars -except Niters memused iter t
> end
>
> plot(1:Niters,memused,'r-o');
> grid on;
> fprintf('Max = %d, Min = %d, Diff = %d\n',max(memused),min(memused),max(memused)-min(memused));
>
> t = fix(etime(clock,t));
> fprintf('Elapsed time = %d seconds..\n',t);
> end
>
> function runLeakingCode()
> x = 0:0.01:7;
> y = sin(x);
> z = cos(x);
>
> figStringA = 'Figure A';
> figStringB = 'Figure B';
>
> hFigure2 = figure(200);
> clf;
> set(hFigure2,'name',figStringA);
> annotation('textbox',[0 0.00 1 0.05],'VerticalAlignment','bottom','FitHeightToText','off','LineStyle','none','Margin',2,'String',figStringA,'FontSize',7);
> annotation('textbox',[0 0.95 1 0.05],'VerticalAlignment','top','FitHeightToText','off','LineStyle','none','Margin',2,'String',figStringB,'FontSize',7);
> subplot(2,1,1);
> plot(x,y);
> grid on;
> subplot(2,1,2);
> plot(x,z);
> grid on;
> end


Instead of closing your figures within the loop, try to clf the current figure and reuse the same figure window. This would also be better for performance. Even better, reuse all the internal handles as well (annotations, axes) such that instead of clf you would simply modify their internal properties - this would run much faster and would also remove the leak.

I suspect that the current memory leak that you see may be due to the fact that Matlab does not properly destroy the figures' resources upon closing, and 20KB per iteration (=per figure) seems about right.

Yair Altman
http://UndocumentedMatlab.com
 

Subject: Memory leak in Matlab 2012a?

From: Jesper Holm

Date: 11 Oct, 2012 11:47:07

Message: 4 of 8

[snip]
>
> Instead of closing your figures within the loop, try to clf the current figure and reuse the same figure window. This would also be better for performance. Even better, reuse all the internal handles as well (annotations, axes) such that instead of clf you would simply modify their internal properties - this would run much faster and would also remove the leak.
>
> I suspect that the current memory leak that you see may be due to the fact that Matlab does not properly destroy the figures' resources upon closing, and 20KB per iteration (=per figure) seems about right.
>
> Yair Altman
> http://UndocumentedMatlab.com
>

Thank you for the feedback. The example provided is for sure not the most optimal solution - I just tried to keep things simple.

Your idea regarding reusing the internal handles is good and I will definitely consider it. The downside is that we have thousands of lines of Matlab code that would need to be reworked. The task is furthermore complicated by the fact that figures are annotated based on the data so the number of annotations pr figure is not constant. Hmm...

I guess that our scenario (MCR exe running 24-7) is a bit special use case, but even small leaks "pr figure" will add up over time and eventually crash our MCR

Regards,
Jesper

Subject: Memory leak in Matlab 2012a?

From: Jesper Holm

Date: 12 Oct, 2012 07:13:09

Message: 5 of 8

Well... Seems like MathWorks have confirmed that there is a leak in 2012a. I got the following feedback from tech support today:

"Thank you for the information that you provided. I was able to reproduce this issue at my end in R2012a. It worked absolutely fine in R2012b. It seems to be a known issue in R2012a but not in R2012b with annotation objects and I have forwarded your use case to our Development Team. "

My current findings are so far:

(1) Our 2012a MCR executables (with no figure annotations) => NO LEAKING

(2) Exact same code deployed with 2012b => LEAKING IS BACK (and even worse than before).

I'm not saying that 2012b is the culprit since we are using a privately developed MEX file for interfacing to a MySQL database but I'm basically back to square one and thousands of lines of code to debug :-(

I searched the Matlab bug list but found no relevant info related to leaks in 2012b (and 2012a for that matter). I have asked MathWorks to tell me of other "known issues" (that are not publically available) but I don't think I will get any info.

So... I know this is a long shot.... Do any of you know what to avoid in 2012b in order not to leak memory? ;-)

Regards,
Jesper

Subject: Memory leak in Matlab 2012a?

From: Ernie Scott

Date: 17 Jan, 2013 17:39:17

Message: 6 of 8

Hi Jesper,

I am curious if you ever found a solution to this issue, since I have encountered a similar situation?

I have MATLAB 2012b running 24/7 as an automation server on a 64 bit Windows 7 PC. Data is submitted to MATLAB for processing on a 60 second near real-time interval. If processing results meet alarm conditions, then MATLAB uses a figure window (with many axes and annotations) to generate an image for alarming purposes. There is a memory leak associated with figure window, and eventually this causes the system to run out of memory and crash.

Thanks,

Ernie

Subject: Memory leak in Matlab 2012a?

From: Jesper Holm

Date: 18 Jan, 2013 07:44:09

Message: 7 of 8

Hi Ernie,

The short answer is unfortunately 'NO'. I ended up removing all annotations from our figures since this was the only "quick fix" available. Rather annoying, but not critical for our product.

Our code is therefore currently not leaking memory but for safety I have added regular calls to the Matlab MEMORY function. If the Matlab memory usage exceeds a predefined maximum value the MCR executable will do a graceful exit and terminate (this seems to free the memory). A simple DOS batch script will then re-launch the MCR executable.

This is a really ugly solution but it's better than an unpredictable crash.

My hope is that Mathworks sooner or later provides a fix since they have confirmed the problem to exist in 2012a. If I (ever) find some time I would really like to do a more thorough analysis on 2012b and push Mathworks for a solution.

If you have more luck with 2012b please drop a note.

Subject: Memory leak in Matlab 2012a?

From: Ernie Scott

Date: 18 Jan, 2013 15:36:08

Message: 8 of 8

Jesper,

Thanks for the response.

I confirmed that removing the annotations does indeed prevent the memory leak, but the annotations are important in my application, so this is not a viable work around. I will look into your suggestion of monitoring MATLAB memory to implement an alternative work around by closing and reopening the MATLAB automation server, but like you said that is an ugly thing to have to do.

I won't be working on this again for a couple weeks, but if ever understand anything new, I certainly will post it here. I have an easy way to test this, so when the new version of MATLAB comes out this spring I will see if the problem is resolved and let you know.

Cheers,

Ernie

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us