Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are C++ strings stored? [duplicate]

Tags:

c++

string

memory

Possible Duplicate:
std::string and its automatic memory resizing

I am just curious, how are strings stored in memory? for example, when I do this:

string testString = "asd";

it allocates 4 bytes, right? a + s + d + \0.

But later, when I want to assign some new text to this string, it works, but I don't understand how. For example I do this:

testString = "123456789"

Now it should be 10 bytes long. But what if there wasn't space for such string? let's say that fifth+sixth bytes from the beginning of string are taken by some other 2 chars. How does the CPU handles it? It finds completely new position in memory where that string fits?

like image 795
user1145902 Avatar asked Feb 03 '12 17:02

user1145902


People also ask

How are C strings stored?

Overview. The C language does not have a specific "String" data type, the way some other languages such as C++ and Java do. Instead C stores strings of characters as arrays of chars, terminated by a null byte.

How does string copy work in C?

In the C Programming Language, the strcpy function copies the string pointed to by s2 into the object pointed to by s1. It returns a pointer to the destination.

Are C strings stored on the stack?

When strings are declared as character arrays, they are stored like other types of arrays in C. For example, if str[] is an auto variable then string is stored in stack segment, if it's a global or static variable then stored in data segment, etc.

How do you find duplicates in a string?

To find the duplicate character from the string, we count the occurrence of each character in the string. If count is greater than 1, it implies that a character has a duplicate entry in the string. In above example, the characters highlighted in green are duplicate characters.


1 Answers

This is implementation dependent, but the general idea is that the string class will contain a pointer to a region of memory where the actual contents of the string are stored. Two common implementations are storing 3 pointers (begin of the allocated region and data, end of data, end of allocated region) or a pointer (begin of allocated region and data) and two integers (number of characters in the string and number of allocated bytes).

When new data is appended to the string, if it fits the allocated region it will just be written and the size/end of data pointer will be updated accordingly. If the data does not fit in the region a new buffer will be created and the data copied.

Also note that many implementations have optimizations for small strings, where the string class does contain a small buffer. If the contents of the string fit in the buffer, then no memory is dynamically allocated and only the local buffer is used.

like image 183
David Rodríguez - dribeas Avatar answered Oct 02 '22 22:10

David Rodríguez - dribeas