6

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?

Pedro Alves
  • 1,667
  • 4
  • 17
  • 37

4 Answers4

10

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.

Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
md5
  • 23,373
  • 3
  • 44
  • 93
6

When memory is allocated and later free'd, that memory still stays with the process but is marked as free so it can be allocated again. This is because otherwise the operating system have to alter the virtual memory mapping of the process each time you call malloc or free, which takes time.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

free() merely tells the allocator that your program no long needs this block. The allocator may cache it for further allocation, or it may return it to the system by change the brk pointer. It all depends on the implementation.

phoeagon
  • 2,080
  • 17
  • 20
1

When the system memory will be actually released depends on the OS.

Foe example in Windows, even if you close a program, the memory is not released at the same time. It is made in order to reuse it on the next program start.

Alex
  • 9,891
  • 11
  • 53
  • 87