Measure memory usage in c

Asked

Viewed 895 times

2

Hi, can I measure the use of ram memory of a program made in c? Do you have any specific tool or something like?

  • I have no knowledge of any such tool. What you can do to ease RAM consumption is to take advantage of the use of pointers and dynamic allocation, if your problem is running time or memory space, respectively.

  • Each operating system has a different tool to do this. You must specify the system in question to attract more accurate answers.

1 answer

6


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

The following program repeatedly allocates and displaces memory blocks via 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 was 1,000,000 calls from malloc() and of free(), who worked with a total of 1,024,000,000 bytes full-memory.

  • That’s exactly what I needed, thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.