简体   繁体   中英

Get the amount of memory allocated by malloc

Is there an easy way to know the total amount of memory that has been allocated by every malloc in the program? I'm suffering from a memory leak and I want to find out where it is.

There is no way in a standard, operating system neutral, fashion.

But with GNU Glibc you have mallinfo

On Linux systems, you can learn about your virtual memory map thru the /proc/self/maps (or /proc/self/smaps which gives more details) pseudo-file. For process of pid 123 you can read /proc/123/maps

Of course, details are system specific.

To find a memory leak, use a tool like valgrind

By a specific malloc , yes, you have as much memory as you asked for and no more :-)

In reality, it may give you a little more (many implementations will give you a multiple of 16 or 32 bytes) but there's no way to tell in standard C how much. Using more than you asked for is undefined behaviour, no matter what sort of padding goes on.

Some systems have a mallinfo function which you can call to get statistics on the overall memory arena, if you want to know how much memory in total has been allocated. You could look into that but, again, it's not standard.

There's no standard method to do so. Microsoft's C library has a _heapwalk function that you could use to compute it.

You allocated the memory in the first place, just make a note of how much. Perhaps use a struct to store both the pointer and the size.

Use valgrind to help in debugging a potential memory leak.

In you want to do some C debugging, glibc has some functions to help you in debugging with malloc .

Hooks for malloc

http://www.gnu.org/software/libc/manual/html_node/Hooks-for-Malloc.html

Heap Consistency Checking

http://www.gnu.org/software/libc/manual/html_node/Heap-Consistency-Checking.html

Statistics for Memory Allocation with malloc

http://www.gnu.org/software/libc/manual/html_node/Statistics-of-Malloc.html

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