Search code examples
csystem-callsdynamic-memory-allocationxv6

Why do I have different dynamic allocation sizes and output results in xv6?


uint
memsize(void){ // Simply insert the memory size of the current process into size and return size
    uint size;
    struct proc *p;
    p = myproc();
    size = p->sz;
    
    return size;
}
// test_memsize.c
#define SIZE 2048

#include "types.h"
#include "user.h"

int main(void){
    int msize = memsize();
    printf("The process is using %dB\n", msize); // output: 12288B
    
    char *tmp = (char *)malloc(SIZE * sizeof(char)); 
    
    printf("Allocating more memory\n");
    msize = memsize();
    printf("The process is using %dB\n", msize); // output: 45045B
    
    free(tmp);
    printf("Freeing memory\n");
    msize = memsize();
    printf("The process is using %dB\n", msize); //output: 45045B
    
    exit();
}

The memory usage of the current process is 12288B and It was allocated as dynamic as 2048 bytes. But the result is 45045B. Why does this happen? (I'm using xv6.)


Solution

  • In the words of the C17 standard's description of the free() function, 7.22.3.3.2, (Emphasis mine):

    "The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined."

    Implementations of free() may choose to return the malloc/calloc-ated memory to the operating system when free() is called on its pointer, but they are not required to. This allows these implementations to keep that memory so that it may be reallocated in other malloc/calloc calls before the program terminates, preventing the overhead of returning and re-requesting memory pages from the operating system in programs that allocate and free memory often.

    What is happening is your system's implementation of malloc/calloc/realloc/free is asking the operating system for a chunk of memory bigger than you asked for (most likely a page), and choosing to hold onto it after free in case you were to request more memory via malloc/calloc/realloc.