Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do strings allocate memory in c++?

I know that dynamic memory has advantages over setting a fixed size array and and using a portion of it. But in dynamic memory you have to enter the amount data that you want to store in the array. When using strings you can type as many letters as you want(you can even use strings for numbers and then use a function to convert them). This fact makes me think that dynamic memory for character arrays is obsolete compared to strings.

So i wanna know what are the advantages and disadvantages when using strings? When is the space occupied by strings freed? Is maybe the option to free your dynamically allocated memory with delete an advantage over strings? Please explain.

like image 671
Stefan Stojkovski Avatar asked Dec 07 '25 03:12

Stefan Stojkovski


2 Answers

The short answer is "no, there is no drawbacks, only advantages" with std::string over character arrays.

Of course, strings do USE dynamic memory, it just hides the fact behind the scenes so you don't have to worry about it.

In answer to you question: When is the space occupied by strings freed? this post may be helpful. Basically, std::strings are freed once they go out of scope. Often the compiler can decide when to allocate and release the memory.

like image 59
Mats Petersson Avatar answered Dec 08 '25 20:12

Mats Petersson


std::string usually contains an internal dynamically allocated buffer. When you assign data, or if you push back new data, and the current buffer size is not sufficient, a new buffer is allocated with an increased size and the old data is copied or moved to the new buffer. The old buffer is then deallocated.

The main buffer is deallocated when the string goes out of scope. If the string object is a local variable in a function (on the stack), it will deallocate at the end of the current code block. If it's a function parameter, when the function exits. If it's a class member, whenever the class is destroyed.

The advantage of strings is flexibility (increases in size automatically) and safety (harder to go over the bounds of an array). A fixed-size char array on the stack is faster as no dynamic allocation is required. But you should worry about that if you have a performance problem, and not before.

like image 36
Neil Kirk Avatar answered Dec 08 '25 21:12

Neil Kirk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!