Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why free() doesn't really frees memory?

Tags:

c

malloc

free

i'm doing some tests allocating and deallocating memory. This is the code i'm using:

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

#define WAVE_SIZE 100000000

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

    int i;
    int **p;

    printf("%d allocs...\n",WAVE_SIZE);

    // Malloc
    printf("Allocating memory...\n");
    p = (int**)malloc(WAVE_SIZE*sizeof(int*));
    for(i = 0;i < WAVE_SIZE;i++)
            p[i] = (int*)malloc(sizeof(int));

    // Break
    printf("Press a key to continue...\n");
    scanf("%*s");

    // Dealloc
    printf("Deallocating memory...\n");
    for(i = 0;i < WAVE_SIZE;i++)
            free(p[i]);             
    free(p);

    // Break
    printf("Press a key to continue...\n");
    scanf("%*s");

    return 0;
}

During breaks i check the total memory used by the process and i don't see what i expect.

Until the first pause i see memory consumption increasing. However, at second pause I do not see it being released.

Is this a OS thing? What happens if my machine's load is high, i don't have free memory and another process try to alloc?

like image 467
Pedro Alves Avatar asked Feb 28 '13 15:02

Pedro Alves


Video Answer


1 Answers

free does not necessarily release the memory back to the operating system. Most often it just puts back that memory area in a list of free blocks. These free blocks could be reused for the next calls to malloc.

like image 73
md5 Avatar answered Oct 12 '22 20:10

md5