V
V
vladmd022021-09-10 01:18:26
C++ / C#
vladmd02, 2021-09-10 01:18:26

Why is the maximum size of a std::string object 4611686018427387897?

In this piece of code, I'm printing out the maximum length of a std::string object:

string s;
cout<<s.max_size()<<endl;
cout << INT_MAX << endl;
cout<<LLONG_MAX<<endl;


Result of the code:
4611686018427387897
2147483647
9223372036854775807

If it's not difficult, please explain why the maximum size of a std::string is 4611686018427387897.
(That's about half of LLONG_MAX )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-09-10
@vladmd02

Well, it's just that the creators of the library hardcoded exactly this number.
This construction returns different values, depending on the compiler, bitness, operating system.
This is 2^62-7. Why 2^62? Maybe for some reason your system can't address more than 62 bits. Maybe the system uses 2 bits for something. Why -7? You need to store the length somewhere else, you need to leave room for the null character at the end, and you need to leave the std::string::npos index untouched - this value is used to indicate "non-existent index". The exact meaning depends on what the programmers of the standard library have done there.
In any case, this value is many, many orders of magnitude larger than any practically possible string length. Well, you can't allocate 4 exobytes of memory.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question