cancel
Showing results for 
Search instead for 
Did you mean: 

Memory leak in an example?

MichaelM
Associate

Just came across this in one of my pet projects.

https://support.touchgfx.com/docs/development/ui-development/ui-components/containers/list-layout

void Screen1View::setupScreen()
{
    Screen1ViewBase::setupScreen();
    //listLayout1.setWidthHeight(0, 0); // Remove excess space in List Layout
    for (int i=0; i < 3; i++)
    {
        TextArea *textArea = new TextArea();
        textArea->setWidthHeight(100, 25);
        textArea->setTypedText(touchgfx::TypedText(T_RESOURCEID1));
        listLayout1.add(*textArea);
    }
    listBackground.setWidthHeight(listLayout1);
}

Surely the fact that textArea pointer is not recorded anywhere indicates a memory leak.

Three dynamic allocations happen in the loop, and pointers are passed to listLayout1.add()

There is no way these three memory blocks can be de-allocated. The listLayout cleanup function could not possibly do the delete of added textArea objects, given it cannot assume blocks were dynamically (and not statically, or on stack) allocated. In fact I tried that (adding globally allocated textAreas to listLayout and no crash occurs so no surprise there).

And this leak will happen every time the screen is entered.

So correct code IMO would have been to store each pointer as a member of the class and delete in tearDownScreen

I understand this is only a little example but people may end up copying and pasting this stuff into their work...

3 REPLIES 3
LouisB
ST Employee

Hello @MichaelM ,

Thanks for your contribution, I will talk about it to the team.

Regards,

Louis BOUDO
ST Software Developer | TouchGFX

>>I understand this is only a little example but people may end up copying and pasting this stuff into their work...

Indeed, would probably be helpful to illustrate the constructor / destructor pairs for these things, and how to keep them in-sync, or keep track of the number instances they allocate rather than use constants / defines.

One might hope C++ coders are sufficiently aware that things need to be torn-down / unwound when done.

But a lot of Cargo-Cult and Chat GPT coders with relatively superficial understanding of such problems.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
ferro
Senior III