Question

I'm working on an assignment that concerns where things are located in memory, static, stack, or heap. I understand the basics, but am confused by questions such as the following:

A character that is stored in a C++ string object if the object is a local variable of a public member function of a class.

I'm confused by how I would go about determining where in memory such a character is stored. I expect an activation record for a function to be pushed to the stack, the string then is part of that activation record, and therefore the associated characters are also on the stack. Is this correct?

Is there a general way to approach this? Should I even be concerned with all the outer layers or is there a way to sufficiently deduce where something is stored in memory without concerning myself with all of the nuances of where it is stored in the code?

Was it helpful?

Solution

Not necessarily. If you declare a std::string on the stack (as a local variable, say), then all of its member variables are located on the stack. Its member variables likely include a length field and a pointer to the character array. (This is up to the implementation of the standard library: the standard does not define exactly what private members a std::string must have.)

The characters themselves are not on the stack, though. std::string dynamically allocates its memory using new, so the character data is on the heap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top