Check out these two C codes:
char* char_pointer;
int* int_pointer;
char_pointer = (char*)malloc(5);
printf("location of char_pointer: %p\n", char_pointer);
int_pointer = (int*)malloc(10);
printf("location of int_pointer: %p\n", int_pointer);
free(char_pointer);
char_pointer = (char*)malloc(50);
printf("location of char_pointer: %p\n", char_pointer);
and
char* char_pointer;
int* int_pointer;
char_pointer = (char*)malloc(200);
printf("location of char_pointer: %p\n", char_pointer);
int_pointer = (int*)malloc(10);
printf("location of int_pointer: %p\n", int_pointer);
free(char_pointer);
char_pointer = (char*)malloc(50);
printf("location of char_pointer: %p\n", char_pointer);
The outputs are:
location of char_pointer: 0x23eb010
location of int_pointer: 0x23eb030
location of char_pointer: 0x23eb050
and
location of char_pointer: 0x1815010
location of int_pointer: 0x18150e0
location of char_pointer: 0x1815010
As you see, in first program, it decided to allocate char_pointer after int_pointer(after I freeing and reallocating) but in second program it decided to allocated char_pointer in place of freed memory 0x1815010.
The only difference between programs is the amount of memory allocated and freed.
So, my questions are:
What does the decision of allocation place depend on? (OS, compiler or hardware)
Why does "it" make a decision to allocate in place of freed memory if the amount of allocated memory is "big"?
P.S. I have read about this issue in this book