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);
Outputs:
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 can see, in the first program he decided to allocate char_pointerafter int_pointer(after the release and redistribution), but in the second program he decided to allocate char_pointerinstead of the freed memory 0x1815010.
The only difference between the programs is the amount of allocated and freed memory.
So my questions are:
What determines the placement decision? (OS, compiler or hardware)
Why does "he" decide on allocation instead of freed memory if the amount of allocated memory is "large"?
PS I read about this problem in this book.