View Full Version : proper use of QList?

13th September 2010, 03:05
I am trying to implement a history of structures--I want to maintain a list of them, with a given maximum size. As a new structure arrives, I want to remove the oldest, and add the new one. In other words, a FIFO.

I am using a QList. Until I reach my maximum size, as new data arrives, I malloc a structure, fill it, and list.prepend() the pointer to the list. Forgive me for mallocing structures instead of creating new objects, I am at heart a C programmer, and this is legacy code being fit into a new QT app.

Once I reach my maximum size, as new data arrives, I use list.takeLast(), and use the returned data (the pointer to my previously malloc'd structure) for my new data. I prepend that to the list. I am trying to avoid continual new memory allocation, as these operations happen quickly, and my program typically runs for many days.

While this appears to do what I want, I also seem to have a memory leak. Why would this be? Am I doing something really stupid?

Thanks for any help.

13th September 2010, 04:31
you remove item from the qlist which is a pointer,the qlist only removes the pointer,but the data of pointer have not been released,so cause memory leak

13th September 2010, 12:03
@foxhengxing: That's not it. He is reusing the structure for the new data and prepends it. The whole thing is a preallocated cyclic list.

I am not sure, but the way I see it, you are moving the list always backwards, so QList needs to expand its internal array. QList is not a pointerlist! Do you need access by index? Look into QLinkedList if not.

Maybe you could also use QContiguousCache? Seems to be optimized for the paired appending/prepending. In combination with your preallocated data pointers that could do the trick.

For testing purposes you could make your structure really big and see if your memory leak scales with it.


13th September 2010, 15:57

I was unfamiliar with QContinuousCache, and you are right, it seems to be exactly what I need to use--thanks very much.