How can C++ make it possible to use dynamic container classes even in embedded systems?
Background info:
I’ve been working with PIC (C) and AVR (C++) processors and at the moment (PIC C) I’m trying to send a text (with undefined length) to a method that only sends this string with a HTTP POST (so it has to know the length beforehand).
Problem & question:
On C++ this could easily be achieved with a container class/dynamic array.
Though, when using C, I (guess) I’m continiously overwriting memory addresses (When I use a pointer and then change the length)?
How does C++ (efficiëntly?) manage dynamic arrays? Are all bits off the dynamic array scattered throughout your memory and how does it find these back? Or does it secretly allocate memory/blocks of memory?
2
C++ can do it the same way C does. All C++ gives you is easier-to-use containers that wrap much of the low-level detail.
For example, a string class can (and does) hold a block of memory on the stack for short strings, only allocating a heap buffer for larger ones. This buffer is exactly like a C string buffer, if the string resizes, the string class will resize it in the same way a C programmer would by allocating a new buffer and copying the old data into it, except that possibly the string class will over-allocate the buffer size to allow for future appending to the string. Some string classes will count the length of the string using strlen, others will store the length as a member variable that it keeps up to date.
Arrays are managed in the same way, but there are specialised containers that give you things like linked lists.
7