1

The following places a bunch of shared_ptrs containing an arbitrary object in a QList. With the curly braces I create a stack, which triggers the deletion of the list when the instruction pointer leaves it. Somehow the shared_ptrs get not deleted. Why? I track the memory consumption in gnome-systemmonitor and htop.

{
    QList<std::shared_ptr<QChar>> l;
    for (int i =0; i< 1024*1024*10; ++i)
        l.append(std::make_shared<QChar>('h'));
}
qDebug() <<"done";
sleep(10);

I just tested it. The same problem with QSharedPointer, but not with regular types (non [shared] pointers).

ManuelSchneid3r
  • 15,850
  • 12
  • 65
  • 103

2 Answers2

2

Small memory allocations come from a heap managed within the process, not directly from the operating system. Tools that measure the process's memory usage won't see them being deallocated, since the memory is still allocated to the process.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • This about some hundreds of megabytes. If still true when will they be deallocated? – ManuelSchneid3r Apr 29 '15 at 14:38
  • @ManuelSchneid3r: Each allocation is a single byte, so it will come from the heap. The heap memory will be deallocated when the process exits; or possibly earlier, if the heap manager is able to detect and release unused blocks of memory. I've no idea whether any heap managers actually do that. – Mike Seymour Apr 29 '15 at 14:40
  • Unbelievable, so my about 10 MB application blocks 1GB of ram because of an expensive initialization and I can not do anything about it? – ManuelSchneid3r Apr 29 '15 at 14:46
  • @ManuelSchneid3r: There are plenty of things you can do about it; find a way to structure your data so you don't have so many tiny allocations. Or use a pool (like [this](http://www.boost.org/doc/libs/1_58_0/libs/pool/doc/html/index.html)) rather than the heap. – Mike Seymour Apr 29 '15 at 14:48
2

Freeing memory doesn't necessarily return it to the system. Depending on how the default allocator requests memory from the system, it may not be possible to return it.

If you want to track whether memory is being freed correctly, use a counting allocator, not a system monitoring tool.

ecatmur
  • 152,476
  • 27
  • 293
  • 366