0

I understand that static variables are allocated in the data segment (not in stack and heap).

std::map< std::string, testClass*> TestMap;

static TestMap testMapInstance;

Here testMapInstance is a dynamically growing map. Where we push testClass which is allocated via new (heap).

How does compiler allocate this static variable and where? What is the memory limit in this case (how much this map can grow)?

2

3 Answers 3

3

While the std::map object itself might be in a data-segment, the key-value storage is not allocated there.

It simply can't be since the number of key-value pairs is not known at compile-time, only on run-time.

Therefore the key-value pairs have to be dynamically allocated of the heap.

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

Comments

2

It's probably worth reminding yourself that std::map<K, V> is actually this:

std::map<K, V, Pred, Alloc>

Since you haven't mentioned Pred in your map declaration it defaults to std::less<T>.

Similarly Alloc defaults to std::allocator<std::pair<const Key, T> > where std::pair<const Key, T> is the implied value_type of your map.

It is the class denoted by Alloc that determines how and where the values in the map are allocated.

std::allocator<X> uses ::operator new and ::operator delete to allocate and deallocate memory. Unless you have redefined those, memory will be managed by the heap.

You can override this by specifying your own custom type for Alloc. Doing this successfully however is something of a dark art. You may want to read up on it before you try.

ref: http://en.cppreference.com/w/cpp/concept/Allocator#Allocator_completeness_requirements

1 Comment

I would presume that generally, users asking such questions cannot, and should not, write a custom allocator.
1

Your variable is in the static data area, but he map will also allocate additional space from the heap when it grows.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.