1

I wonder how visual c++ std::string is populated in memory.
For example if I declare std::string container[10] in a shared memory region, then can I insert any length of string into this array at run-time ?
Since it is known that shared memory region can not expand at run-time, then how can we insert varying size of strings into this array ?

8
  • 1
    Are you talking about memory shared between multiple processes or something else? If you are, it won't work without a custom allocator at the very least. std::string will perform heap allocations (which won't be in the shared area by default) so any process trying to access the strings (other than the one that constructed them) will fail. Commented May 8, 2014 at 5:52
  • Thanks for your points. Yes about memory shared between 2 processes. Now it is more clear. Just to be sure that I got the point, I wanna ask that, when a shared memory region created with a field std::string sample[10], then how much memory is allocated for this purpose. For example, it would be clear if it was array of char, int, float etc. Because their sizes are already known at compile time. I wonder the case with std::string. Commented May 8, 2014 at 6:04
  • Allocators will allow you to put strings in shared-memory.. However, the size of the shared memory MUST be known before hand.. Otherwise you need to make the allocator create a new set, copy the old memory into the new one.. Example allocator: stackoverflow.com/questions/23459142/… Commented May 8, 2014 at 6:24
  • @Brandon: I understand how the custom allocator allows to place an allocation into shared memory. But for a string, you really have two "items". The string object, and the memory allocated by the string to hold the characters. Say you manage to place both of these in the shared memory. Then you map the shared memory into two processes, which generally get two different virtual addresses that point to the shared memory. What happens when both access the string, and the string then accesses its pointer to the characters? The two processes have the characters at different virtual addresses. Commented May 8, 2014 at 7:16
  • ... The only way I can see this working is if you force the shared memory to be mapped to the same virtual address in both processes. Or am I missing something? Commented May 8, 2014 at 7:17

1 Answer 1

1

That sounds like a really bad idea. std::string involves dynamic memory allocation, pointers, etc. If you have two processes that run in separate address spaces accessing it, I don't see how that could work.

Sign up to request clarification or add additional context in comments.

2 Comments

when we declare std::string var, is it allocated on stack or on heap ?
var is stack allocated. var's internal memory is heap allocated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.