1

I am trying to initialise a vector as follows:

vector<int> vect(n, 2);

This statement initialises vect to contain n elements of type int with value 2. n is a variable of type size_t that has been checked to ensure n <= vect.max_size() is always true.

I am currently testing my code so far on Code::Blocks. It works for any arbitrary small value of n, but when I try to run it in the IDE at n = vect.max_size(), the program terminates, saying an unknown application error occurred, and to speak to the developer (me).

Does anyone know what is wrong? Is this not the right way to initialise the vector to the maximum size possible in runtime? I checked, my math is correct, n didn't exceed vect.max_size()

thegreatjedi
  • 2,788
  • 4
  • 28
  • 49
  • What happens if you try `vect.max_size() - 10`? It might help shed some light on the issue. – therainmaker Dec 11 '15 at 10:43
  • 3
    Do you have 17 GB of RAM? – Simple Dec 11 '15 at 10:44
  • When you create a vector type variable specifying the size, all the memory will be allocated at once ... max_size() function returns to you how big this vector could be regardless of your current memory size ... so currently you allocate GB of memory on the heap, and you just simply run out of resources ... – Avi Dec 11 '15 at 11:10
  • If you go above `max_size()`, the allocation will *always* fail. If you are below `max_size()` the allocation might work, sometimes. The odds for it working is greater the further below you get, and the fewer other allocations you have done previously. So, not a very useful function... – Bo Persson Dec 11 '15 at 12:11
  • Is there a good way to determine what's the runtime max for n, or at least a close and safe approximation? That's what I really mean to do in the first place when I used max_size, because I thought it is a practical limit compared to the even more theoretical (size_t)-1 – thegreatjedi Dec 11 '15 at 14:00

1 Answers1

2

The max_size() members are somewhat theoretical limits. On machines with large amounts of memory it may be possible to create containers with the corresponding size but typically it won't be possible with modern technology.

The reason for the existence of max_size() is pretty much lost in the mists of history. I suspect that the value was sort of meaningful when STL was developed and a container was instantiated with a "small" pointer (something like __small int*): at around that time some platforms had pointer types of different size, e.g., a 16 bit "small" and a 32 bit "large" pointer.

I don't think there is a practical way to determine the maximum size of a container which can be allocated. At best you may be able to do something like a binary search, trying to create a container with some size and catching std::bad_alloc: most likely your "application error" and uncaught exception of that type.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380