Measure memory usage in c

2

Hi, how can I measure the ram memory usage of a program made in c? Do you have any specific tools or anything?

    
asked by anonymous 06.05.2018 / 16:37

1 answer

6

You can use valgrind with the --leak-check=full option.

The following program allocates and deallocates memory blocks repeatedly by calling malloc() and free() :

 #include <stdlib.h>


#define TAM_BLOCO    (1024)  
#define QTD_BLOCOS   (1000000)

int main( void )
{
    int i = 0;

    for( i = 0; i < QTD_BLOCOS; i++ )
    {
        char * p = malloc( TAM_BLOCO * sizeof(char) );
        free(p);
    }

    return 0;
}

Compiling:

$ gcc testmem.c -o testmem

Testing with valgrind :

$ valgrind --leak-check=full ./testmem
==27153== Memcheck, a memory error detector
==27153== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==27153== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==27153== Command: ./testmem
==27153== 
==27153== 
==27153== HEAP SUMMARY:
==27153==     in use at exit: 0 bytes in 0 blocks
==27153==   total heap usage: 1,000,000 allocs, 1,000,000 frees, 1,024,000,000 bytes allocated
==27153== 
==27153== All heap blocks were freed -- no leaks are possible
==27153== 
==27153== For counts of detected and suppressed errors, rerun with: -v
==27153== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

According to the output of Valgrind , there were 1,000,000 calls of malloc() and free() , which worked with a total of 1,024,000,000 bytes of total memory.

    
06.05.2018 / 17:31