ssh99
ssh99

Reputation: 309

Limit maximum length of std::string variable

std::string src;
cout<<"maximum length of string : "<<src.max_size();

Output I get is:

maximum length of string : 1073741820

I need to create a large array of strings, like string input[100000], but I get run time error when I use array indices more than 80,000. Length of my string variables are less, average length is 15 characters. So I need to limit the length of the string variable.

Following are my questions:

  1. What factors are considered for deciding the larget index of the string array?

  2. How do I reduce the max_size() of string variable?

Upvotes: 0

Views: 3268

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

You have jumped to a wrong conclusion. std::string::max_size() is not representative of current memory usage and it is not contributing to your runtime error. It is an implementation quantity that tells you the maximum possible size of a string on your system: you cannot change it, and you do not need to.

You are smashing your stack at 80,000 std::strings because stack space is typically quite limited. It is up to your compiler to decide how much stack space will be available in your program. Typically, for an array this large, you would use dynamic or static allocation instead.

A good way to do that is to use the standard containers, e.g. std::vector<std::string>.

Upvotes: 7

Related Questions