Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ maximum std::string length is dictated by stack size or heap size?

Tags:

c++

string

max

as asked in the question.
std::string myVar; the maximum character it can hold is dictated by stack or heap?

Thank you

like image 814
eugene Avatar asked Apr 08 '11 06:04

eugene


2 Answers

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

like image 76
GManNickG Avatar answered Sep 30 '22 21:09

GManNickG


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.

like image 30
Tony Delroy Avatar answered Sep 30 '22 21:09

Tony Delroy