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)?

James Z
  • 12,209
  • 10
  • 24
  • 44
Surya
  • 21
  • 4
  • `testClass` gets allocated in the heap and it's been refered from `TestMap` note you've used `testClass *`. – rakib_ Oct 20 '17 at 11:08
  • Possible duplicate of [When vectors are allocated, do they use memory on the heap or the stack?](https://stackoverflow.com/questions/8036474/when-vectors-are-allocated-do-they-use-memory-on-the-heap-or-the-stack) – underscore_d Oct 20 '17 at 11:10

3 Answers3

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
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

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
1

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

Bo Persson
  • 90,663
  • 31
  • 146
  • 203