I am converting a project from C to mixed C/C++. It is going quite nice, and the
ID: 658565 • Letter: I
Question
I am converting a project from C to mixed C/C++. It is going quite nice, and the new features are really lightening the work.
The platform is an ARM SAM4, compiler is arm-none-eabi-g++. This is not a safety-related equipment, but still could be left running for months and is not supposed to restart sporadically.
The original C project has managed quite nicely to solve problems without a single malloc call, allocating statically all needed data. For example, arrays with unknown size are allocated to the maximum expected size.
Now I am considering can I get away with using new. For example, all STL containers hold their content in the heap. Just adding a new element to a vector can cause de-allocation of a whole region of the heap and allocation of another one.
Will there be fragmentation issues?
Explanation / Answer
Working in a constrained memory environment (something that few of us do these days), it is entirely reasonable to use no heap allocation whatever. And C++ can work very nicely to make that possible.
Yes, the C++ collections for the most part do use the heap, because they are designed to grow without limit. Yes, it is almost impossible to ensure that the heap will never be fragmented, using the default allocator. I would not use it without a lot of prior thought.
This gives you two broad choices. Either stick to non-heap collections (which means std::array), or write your own allocator.
Wrapping existing arrays in std::array brings some benefits, but you will have to decide whether they are worth the effort.
A custom allocator can take advantage of your knowledge of how and when memory should be recovered. That might be by keeping free lists, or by periodic reset, or using pools, or some other strategy. It depends on how valuable the heap is to you.
Regardless, C++ has many other benefits. Perhaps the heap is just one step too far.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.