Note: This is a hypothetical situation I am creating to understand the functioning of program and malloc in C/C++.
Let us say that I allocated 10k integers and they all got allocated contiguously in the memory. Now, I free every alternate element in these 10k integers. Now, I want to allocate a long integer which requires 8 bytes. Since none of the above 5k locations have 8 bytes contiguously, does the program allocate this variable a new memory location? If in future I am going to use only > 4 byte locations then am I just wasting this entire memory? Or does the compiler take necessary steps so that these remaining 5k locations will be contiguous later?
EDIT: To those who marked this as a duplicate. Okay, let us say that it uses paging and it is taking care of fragmentation by remapping the pages to contiguous blocks in physical memory. Even then, it would mean that in virtual memory all those address locations are no longer usable right? So, those memory locations are not usable? Yes I understand that this is a problem of fragmentation etc. My question is the following:
Is there any way the run-time program might know that this issue arises and somehow try and manage its resources in a good way? Since C is a totally compiled language, I don't think this is possible. Does JAVA or C# run-time environment do things like this? Reorganizing their objects such that they take up a contiguous block of memory in their heap space? And if that happens, do they have to change values of every referencing variable? Since their position on the heap (and effectively their address) is changing?