Cpp

string memory layout

source

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// string.cpp
#include <string>
#include <iostream>

void func(std::string &hello) {
std::cout << hello.size();
std::cout << hello.capacity();
}

int main () {
std::string hello{"hello, world!!!"};
hello += "this is a test";
func(hello);
std::cout << "Program end\n";
return 0;
}

/*
enum { _S_local_capacity = 15 / sizeof(_CharT) };
union
{
_CharT _M_local_buf[_S_local_capacity + 1];
size_type _M_allocated_capacity;
};

## std::sting: memory size:
sizeof(std::string) = 32
*/

debug

1
2
3
4
5
6
7
8
9
10
11
12
13
> g++ -O1 string.cpp -o string
> gdb string

(gdb) br func
Breakpoint 1 at 0x1249
(gdb) run

(gdb) x /4gx $rdi
0x7fffffffda90: 0x000055555556aeb0 0x000000000000001d
0x7fffffffdaa0: 0x000000000000001e 0x00212121646c726f
(gdb) x /s 0x000055555556aeb0
0x55555556aeb0: "hello, world!!!this is a test"

Share