I have a large array and I expand it with realloc() and use valgrind to see memory usage.
here is minimal example:
#include <stdlib.h>
#include <stdio.h>
#define PASSES 1024 * 2
#define MEMTOALLOC 1024 * 1024
int main(void) {
void *remem = NULL;
void *newmem;
const unsigned int chunk = MEMTOALLOC / PASSES;
unsigned int i;
for(i = 0; i < PASSES; i++){
const unsigned int size = (i + 1) * chunk;
newmem = realloc(remem, size);
if (newmem == NULL){
printf("No memory!\n");
exit(1);
}
remem = newmem;
if (i % 1000 == 0)
printf("%10u processed\n", i);
}
free(remem);
}
If PASSES is 1, program realloc everything at once and valgrind reports:
total heap usage: 1 allocs, 1 frees, 1,048,576 bytes allocated
If PASSES is 100, program realloc gradually with 100 reallocs and valgrind reports:
total heap usage: 100 allocs, 100 frees, 52,949,250 bytes allocated
and if I do PASSES 1024, I get huge consumption:
total heap usage: 1,024 allocs, 1,024 frees, 537,395,200 bytes allocated
What is the explanation of this memory usage?