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?
1 Answer 1
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.
-
1So basically in C++ there are functions that re-locate your memory runtime?aaa– aaa2015年04月07日 14:22:39 +00:00Commented Apr 7, 2015 at 14:22
-
1@FuaZe Yes, but C has functions for that too.Doval– Doval2015年04月07日 14:31:02 +00:00Commented Apr 7, 2015 at 14:31
-
2@Doval I see, but I mean that a C++ string will do this automatically and within C the bound checking/reloallocating is up to you?aaa– aaa2015年04月07日 14:47:33 +00:00Commented Apr 7, 2015 at 14:47
-
1@FuaZe Someone had to write the code in the C++ string implementation to do bound checking and reallocating. Other than syntactic sugar for operators like
+
and automatic conversions fromchar *
tostring
, there's no magic going on.Doval– Doval2015年04月07日 16:06:44 +00:00Commented Apr 7, 2015 at 16:06 -
Thanks for the extra nuancuation! It sometimes looks like Magic though, no, to be honest I was thinking hoe it was implemented also. Didn't think of simply reallocating, haven't done that much runtime allocating (or well I did so, withouth knowing in C++). Was thinking they might have saved the locations of pieces of storage somewhere. Or pointer to the next piece, but that differs per implementation. Reallocating seems fair, but I know start to see the overhead of soms C++ functionsaaa– aaa2015年04月07日 16:20:10 +00:00Commented Apr 7, 2015 at 16:20
malloc
/realloc
or their C++ equivalents.