cmallocvalgrindfreedynamic-allocation

Valgrind shows more memory allocated than actually is


I was writting some simple code in C to test some memory allocation and pointers:

#include <stdlib.h>
#include <stdio.h>


int *randomAlloc(int n) {
    int *address = NULL, i = 0;

    address = malloc (n * sizeof(int));
    for (i = 0; i < n ; i++){
        *(address + i) = i ;
    }
    return address;

}

int main(int argc, char* argv[] ) {

    int *address;
    int n;
    printf("Type vector size: ");
    scanf("%d", &n);
    address = randomAlloc(n);

    free(address);
}

Yet for some reason when I type 4 as input valgrind outputs:

==2375== Memcheck, a memory error detector
==2375== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==2375== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==2375== Command: ./a.out
==2375== 
Type vector size: 4
==2375== 
==2375== HEAP SUMMARY:
==2375==     in use at exit: 0 bytes in 0 blocks
==2375==   total heap usage: 3 allocs, 3 frees, 2,064 bytes allocated
==2375== 
==2375== All heap blocks were freed -- no leaks are possible
==2375== 
==2375== For counts of detected and suppressed errors, rerun with: -v
==2375== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

There is only one alloc and one free at the code. As n = 4, I'd expect it to alloc 4*4(sizeof(int))=16 bytes. Where is this comming from?


Solution

  • Valgrind keeps track of all memory allocations which occur in your application, including ones made internally by the C library. It is not (and cannot) be limited to allocations you make explicitly, as the C library can return pointers to memory which it has allocated internally.

    Many standard I/O implementations will allocate buffers for use by printf() and/or scanf(), which is probably what accounts for the numbers you're seeing.