Virtually defragment a fragmented memory as if it was contiguous in c++

Viewed 101

is there a way or is it possible to take e.g 10 memory regions (e.g. pointers with given size) and create a sort of overlay such that they can be handled/treated as contiguous?

The use case would be something like reconstruct a message out of "n" frames without copying them around. Of course the "n" frames are appended/prependend with a header which should be stripped in order to reconstruct the information. Moreover a variable could be e.g. splitted across two consecutive frames.

Few more details for future help.

Otter solution is quite nice but it lacks the possibility to lay a structure on top of multiple boost::join-ed block. Of course a std::copy of the joined block will create a contiguous copy of all the interested and fragmented regions but in my case i would like it to be "virtual" due to performance constraints.

Regards,

1 Answers

boost::range::join is a great helper here - link. When working with random access ranges it will also produce random access range with quick access to elements. As the manual tells The resultant range will have the lowest common traversal of the two ranges supplied as parameters

Also when working with plain memory boost::make_iterator_range cound help.

Take a look at this short example.

int arr1[] = { 0, 1, 2, 3, 4, 5 };   // let's join these 3 plain memory arrays
int arr2[] = { 6, 7, 8, 9 };
int arr3[] = { 10, 11, 12};

int* mem1 = arr1;  // let's make the example more complicated 
int* mem2 = arr2;  // because int arr1[] with known size will be recognized 
int* mem3 = arr3;  // as a range by boost::join

auto res1 = boost::range::join(boost::make_iterator_range(mem1, mem1 + 6),
    boost::make_iterator_range(mem2, mem2 + 4));    // join 2 ranges by pointer arithmetics
auto res2 = boost::range::join(res1,                // join previously joined range
    boost::make_iterator_range(mem3, mem3 + 3));

for (auto& r : res2)        // the resulted range is iterable
{
    std::cout << r << "\n";
}
std::cout << res2[12];      // outputs '12', note that this result
                            // was eventually got by pointer arithmetics
                            // applyed to mem3
Related