I am relatively new to 'C' and this doubt has been bugging me for days. Hope you guys can come to the rescue!
I can't seem to fathom how and when malloc( ) decides between recycling the memory that was previously allocated, now freed from the same process and requesting the OS for a new page(s). Can you guys help me understand the underlying mechanism? It will be greatly appreciated!
Here is a sample test code I have:
#include <stdio.h>
#include <stdlib.h>
int main(){
char *ptr;
int mem_size1, mem_size2;
printf("\nEnter the size (in bytes) for malloc: ");
scanf("%d", &mem_size1);
ptr = (char *)malloc(mem_size1);
if (ptr!=NULL){
printf("\nAllocated %d bytes at addr=%p\n\n", mem_size1, ptr);
}
free(ptr); //free-up the addresses for re-allocation
printf("\nAgain, enter the size (in bytes) for malloc: ");
scanf("%d", &mem_size2);
ptr = (char *)malloc(sizeof(char)*mem_size2);
if (ptr!=NULL){
//check if the memory address is being re-allocated
printf("\nAllocated %d bytes at addr=%p\n\n", mem_size2, ptr);
}
free(ptr); //free-up the addresses for re-allocation
return(0);
}
Here is my output sequence:
Case I: With 10 bytes as the initial allocation size and 24 bytes as re-allocation size
Enter the size (in bytes) for malloc: 10
Allocated 10 bytes at addr=9C7010
Again, enter the size (in bytes) for malloc: 24
Allocated 24 bytes at addr=9C7010 //Same address space is being reused
Case II: With 10 bytes as the initial allocation size and 25 bytes as the re-allocation size
Enter the size (in bytes) for malloc: 10
Allocated 10 bytes at addr=23F6010
Again, enter the size (in bytes) for malloc: 25
Allocated 25 bytes at addr=23F6030 //Different address space
I am using a 64-bit Linux OS and my system pagesize is 4096B.
So, I do not understand why a completely new address space from the OS is being requested by the malloc( ) in Case II even when the re-allocation requests exceeds only by a byte. Thanks!
It depends on the malloc implementation, but one of the techniques involve allocate a heap space and have a pointer to the top of the heap. the memory returned must be continous, and it can increase the size of the heap when needed.
From this malloc implementation based on sbrk syscall
If you free your pointer you may get a free space in the middle of a continuous space, in this case the malloc simply marks the space as free, and then in a next allocation malloc finds the next continuous space big enough to hold the allocation you asked: