Simone
Simone

Reputation: 2311

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.

Upvotes: 4

Views: 3997

Answers (5)

ouah
ouah

Reputation: 145829

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

Upvotes: 0

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

Upvotes: 3

Ed Heal
Ed Heal

Reputation: 59997

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.

Upvotes: 0

Eric Brown
Eric Brown

Reputation: 13932

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

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881163

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.

Upvotes: 2

Related Questions