Search code examples
cmallocfreedynamic-memory-allocation

How to know the full size of memory allocated for a single program in C?


To check the program total memory allocated at end of a program, Since i used free() function for deallocating an array .


Solution

  • There is no standard way to know that, and the notion of "full size of memory" is not well defined (and its "allocation" could happen outside and independently of malloc, e.g. on Linux by direct calls to mmap(2) etc...)

    In practice (assuming your code is running in a process on some common operating system on a desktop or laptop), think instead in terms of virtual address space.

    Read Operating Systems: Three Easy Pieces (freely downloadable).

    On Linux (but this is Linux specific) you could use /proc/ (see proc(5) for details) to query the kernel about the virtual address space and the status of some process. For a process of pid 1234, see /proc/1234/maps and /proc/1234/status etc.

    You could (and probably should) use valgrind to hunt memory leaks.

    With GNU glibc, you also have mallinfo(3) & malloc_stats(3) (but they are non-standard) etc...

    Be aware that malloc and free uses lower-level system calls such as mmap(2) & munmap (or the older sbrk(2), etc...) to change the virtual address space, but that free usually don't release memory to the kernel with munmap but prefers to keep and mark the freed memory zone for future usage by malloc.

    You could use other implementations of malloc if you really wanted to (or even provide your own one). But you generally should not.