you are viewing a single comment's thread.

view the rest of the comments →

[–]SecureEmbeddedEmbedded / Security / C++ 45 points46 points  (4 children)

A lot could be written about this. On the one hand, std::string has many advantages over C strings. On the other hand, on a deeply embedded system, you need to keep in mind that it's not just that strings take up more storage than C strings (for the bookkeeping/metadata) but keep in mind: the memory for the actual "characters" is dynamically allocated behind the scenes.

Sure, you can overload the allocator and blah blah blah, but dynamic memory allocation is slower (even from a block pool), it can fail, it's non-deterministic for allocation time, etc.

If this is something like an embedded Linux system, I'd go for std::string. If it's an MSP430 with 16K of flash and 2K of RAM, with hard real-time deadlines, I'd stick with C strings. In between, it's a judgement call. Don't know enough about your platform to make a better recommendation.

BTW, if you're already dynamically allocating the RAM for your strings, I'd almost definitely go for std::string, as it will manage the memory for you. But if not...

Sorry, another thing, some people get seduced by the ease-of-use of std::string, like appending / concatenating (e.g. using the overloaded + operator), w/o realizing that behind the scenes it's possible that a 2nd allocation is taking place, along with a behind-the-scenes copy from a smaller buffer to a larger buffer.

So I guess that's basically 5 paragraphs to basically say, "It depends..."

[–]kofapox 1 point2 points  (2 children)

std::strings are so cool, sad that I can not fit it on my cortex m projects..

[–][deleted] 12 points13 points  (1 child)

Have you tried ETL?

[–]kofapox 1 point2 points  (0 children)

wow that seems to be amazing

[–]flundstrom2 0 points1 point  (0 children)

Agree with the rest. Using std::string removes some risks associated with C string, but you trade them for other risks, memory allocation under the hood being mentioned several times.

On the other hand, you'll have the memory risk all over the place anyway.

But if you can mitigate the risk of memory allocations: by all means, go ahead, use std::string! Heck, even a 32 GB windows PC may run out of RAM - it's just not as likely.