eugene
eugene

Reputation: 41665

Is the maximum std::string length dictated by stack size or heap size?

std::string myVar;

Is the maximum character myVar can hold is dictated by stack or heap?

Upvotes: 7

Views: 3679

Answers (2)

Tony Delroy
Tony Delroy

Reputation: 106096

A std::string object will be allocated the same way an int or any other type must be: on the stack if it's a local variable, or it might be static, or on the heap if new std::string is used or new X where X contains the string etc..

But, that std::string object may contain at least a pointer to additional memory provided by the allocator with which basic_string<> was instantiated - for the std::string typedef that means heap-allocated memory. Either directly in the original std::string object memory or in pointed-to heap you can expect to find:

  • a string size member,
  • possibly some manner of reference counter or links,
  • the textual data the string stores (if any)

Some std::string implementations have "short string" optimisations where they pack strings of only a few characters directly into the string object itself (for memory efficiency, often using some kind of union with fields that are used for other purposes when the strings are longer). But, for other string implementations, and even for those with short-string optimisations when dealing with strings that are too long to fit directly in the std::string object, they will have to follow pointers/references to the textual data which is stored in the allocator-provided (heap) memory.

Upvotes: 2

GManNickG
GManNickG

Reputation: 503855

By default, the memory allocated for std::string is allocated dynamically.

Note that std::string has a max_size() function returning the maximum number of character supported by the implementation. The usefulness of this is questionable, though, as it's a implementation maximum, and doesn't take into consideration other resources, like memory. Your real limit is much lower. (Try allocating 4GB of contiguous memory, or take into account memory exhaustion elsewhere.)

Upvotes: 9

Related Questions