When we define a string and then get user his/her name , what is happening in memory.I mean:
Code:
string s;
cout << "Enter name";
cin >>s;
Here s is a ponter and it is in the stack and points to name data which user enter is in the heap.
If allocation in stack:
here s's size is unknown so how can it be How can string class allocate memory in stack that unknown size If this is not possible it seems that string data must be allocated always in heap.
Are these true
I aml ooking for your answers.
Thanks

strings allocate in stack or heap?
Ashok Kumar MVN
MichaelHight
Please note that in new STL (Visual Studio 2003 and 2005), the std::string class uses a combined variant of allocating strings. If the length is long then the string is allocated in heap area, but if is short, it is stored in a preallocated area of the class, i.e. in a data member declared as "char s[...]". (That's why sizeof(std::string) returns an apparently too big value: 32).
This is done for performance reasons. Whe should take this into account when we work with collections of strings.
So we can say std::string allocates short strings on the stack, but long ones -- on the heap.
In the original sample, if the user enter a short string, (shorter than 16 characters), then the string will be stored in a buffer within s, i.e. on the stack. Otherwise the string will be allocated on the heap, and s will keep pointers to that zone.
BobCa
viorel can you give me please link for this information.
Thanks again
Good works..
Photius
Jaalenn
bdp973
ennisb
I don’t have a link for this information. I only analyzed the implementation of basic_string class from xstring file and debugged some simple programs.
The implementation can change from version to version.