Memory leak in QGraphicsScene.
-
It gives a memory leak. What am I doing wrong?
QGraphicsScene *scene = new QGraphicsScene;
ui->graphicsView->setScene(scene);while(true) { QGraphicsEllipseItem *ell = new QGraphicsEllipseItem; scene->addItem(ell); for(auto item : scene->items()) delete item; }
-
@Anton-Shelenkov
A memory leak or a memory error? -
@Anton-Shelenkov
Aren't you supposed to callscene->removeItem(item);
if you want todelete
it yourself, else the scene won't know it's gone/clean up resources properly, no? (That's why I thought your code would crash.) Mind, I've never usedQGraphicsScene
... -
Hi and welcome to devnet,
removeItem
removes the item from the scene, after that, it's the caller's responsibility to delete the item.What gives you that memory leak ?
What OS are you running on ?
What version of Qt are you using ? -
You have an infinite loop where you allocate and delete stuff that chokes Qt's own event loop as it doesn't allow to run anything.
Also, the OS doesn't necessarily reclaim immediately the freed memory.
-
@Anton-Shelenkov said in Memory leak in QGraphicsScene.:
During the program I see in windows task manager how it requires more memory.
That's not how to test properly for a memory leak.
It did not occur to me that the code was the actual program you were running --- I assumed it was a "skeleton" representing the code you were actually running! -
@Anton-Shelenkov
Yes, but these examples are simply not as complex as whatQGraphicsScene::addItem()
is doing, at least book-keeping-wise, behind the scenes, e.g. "taking ownership" of the item --- how do you know what that involves?At absolute minimum: firstly, you must try:
for(auto item : scene->items()) { scene->removeItem(item); delete item; }
And secondly, exactly as @SGaist says, you must address:
You have an infinite loop where you allocate and delete stuff that chokes Qt's own event loop as it doesn't allow to run anything.
e.g. at least allow Qt event loop to run suitably.
-
@Anton-Shelenkov said in Memory leak in QGraphicsScene.:
Thanks all so much, i understood how to do it.
@SGaist I made the loop not infinite and the problem disappeared you were right.Scarily, it seems that @SGaist is always right! ;-)