We're using C++ in an embedded system environment and basically don't want any kind of dynamic memory allocation (see for example Resources for memory management in embedded application for the kind of reasons why we don't). Still we don't want to do without some of nice C++-based features such as STL containers and std::string. For the first one we'd reserve a specific size at initialization and would not let the container grow beyond its capacity. For the latter (std::string) I was a bit skeptical on how to use them "safely" as they sometimes allocate memory on the heap.
I found circumstances, though, where it appears to be fine to use std::string (and generally other of heap allocating objects): I'd allocate the object itself on the stack (within a certain scope delimited by {}
as I'm talking from C++) and allow them to allocate heap provided they actually free all their reserved memory when they get out of scope.
I understand that this method doesn't definitely guarantee freedom of memory fragmentation but I feel that if the scope at hand is short-lived this actually results in a contiguous free memory after the scope's end.
I also had doubts that there may be a problem when multiple tasks sharing the same heap but still the free memory shall be contiguous in the end provided the scopes at hand are all short-lived (do not block for example). Alternatively it would be acceptable to me that only one task is allowed to allocate memory on the heap and the others must not if that actually matters.
Is my suggested usage of heap-allocating objects valid? Does someone have another strategy to (partially) enable dynamic memory allocation without risking memory fragmentation?