Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I worry about memory fragmentation with std::vector?

Tags:

c++

stl

vector

Should I worry about memory fragmentation with std::vector? If so, are there ways to help prevent it? I don't always predict for my programs to be running on a PC, they may also be running on embedded devices/game consoles, so I won't always be able to rely on virtual memory.

Then again I believe it would be more efficient to use a dynamically sized array rather than a static array, so that memory would only be allocated if needed. It would also simplify my programs' design process. Are there ways to achieve this efficiently?

Thanks for any advice!

like image 659
AutoBotAM Avatar asked Oct 31 '11 15:10

AutoBotAM


People also ask

Is memory fragmentation a problem?

Fragmentation is more likely to be a problem when your application makes a series of allocations and deallocations such that each time an allocation is made it cannot re-use space that was left by a previous deallocation of a similar (or larger) size block.

Does vector cause memory leak?

std::vector does not cause memory leaks, careless programmers do. You should also include an example that actually exhibits the behavior you are experiencing, including calls to the CRT debug API. There's a good possibility that you're incorrectly interpreting the leaks based on when they are reported.

Does std::vector allocate memory?

std::vector typically allocates memory on the heap (unless you override this behavior with your own allocator). The std::vector class abstracts memory management, as it grows and shrinks automatically if elements are added or removed.


1 Answers

The answer to your worries may be std::deque. It gives you a similar interface to that of std::vector, but works better with fragmented memory, since it allocates several small arrays instead of a large one. It is actually less efficient than std::vector in some aspects, but for your case it may be a good trade-off.

like image 95
Gorpik Avatar answered Sep 17 '22 13:09

Gorpik