简体   繁体   中英

Get size of memory available on the heap

This is platform dependent question for Linux. And if it matters, I'm asking specifically about pre-C++11.

I want to indirectly test a class's destructor by new and delete to see if all of the memory on the program's heap is deallocated, which could check for memory leaks.

object* x;        //pointer allocated on the stack
...               //measure available heap space
x = new object(); //allocated on the heap
delete x;         //deallocate that heap space
...               //measure again, see if it's the same

I understand that Valgrind has Massif (...is there a C++ library for Massif..?), and that I can even run a memory leak check on my entire program, but code changes. Unit tests are important, and it bugs me to death that I can't fully unit test all of my code.

What code can I write that would measure available heap space?

The distinction between stack and heap are somewhat vague in Linux. Stack is just memory, the top of which, is handed to a clone() call which creates the new task. This is true both for new processes and new threads. The allocator operators are wrappers around system calls brk / sbrk . Your best bet is to override the global operator new / operator new[] and operator delete / operator delete[] to do some sort of counting of the calls in such a way that you can examine it at run time.

A quick read through new expression can give you a good idea of order in which things happen when an object is created/destroyed (forgive me if you already know this) and operator new will tell the order in which allocators are looked up. I may be wrong about this, but in order to have all allocators go through the same point of requesting memory from the OS, even the class-specific operator new would have to eventually call global operator new .

Well, the class-specific ones could use the allocator to mmap memory to a file or shmget to map the object to some storage in shared memory, but in both of those cases it wouldn't be part of what is traditionally referred to as "the heap." The stack+heap both reside in what you see as "VIRT" memory when you run "top" in linux.

Short of that, the memory allocated by malloc and passed to the clone call (which, for instance, creates a new thread) to be the stack of a new thread will not be different from the memory used as heap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM