c++optimizationheap-memoryfragmentation

Will allocations with short lifetimes cause heap fragmentation?


Suppose I have the following:

std::string TestFragmentation()
{
    std::vector<char> buffer(500);
    SomeCApiFunction( &buffer[0], buffer.size() ); // Sets buffer to null-terminated string data
    return &buffer[0];
}

Will the above vector, which allocates memory on the heap, be a cause of memory fragmentation? My understanding of fragmentation is that it only really occurs if you have small, long-lived allocations between larger, more short lived allocations (or vice-versa).

I don't want to prematurely optimize this situation, so I'd like to hear what the general take on code like this should be. I know various experts do not recommend putting large buffers on the stack (that's what the heap is for, after all), so that is usually what I think of first when I write code like this. Fragmentation is normally something that requires analysis. What should my state of mind be here?


Solution

  • If this is the most natural way to express what this code does, then you should do it this way. Unless you have a very unusual situation you haven't told us about, memory fragmentation shouldn't even be on your radar screen yet.