previouslyStringtypesinmemory学习研究Go的字符串在内存中的结构和数据类型。文是两年多前的学习笔记,研究C++字符串在内存中的结构。环境1.操作系统:Ubuntu16.04。2、调试软件:GNUgdb(Ubuntu7.11.1-0ubuntu1~16.5)7.11.1。3、编译工具:g++(Ubuntu5.4.0-6ubuntu1~16.04.11)5.4.020160609。string类的定义定义在/usr/include/c++/5/bits/stringfwd.h头文件中,如下:typedefbasic_stringstring;basic_string类的定义是通过泛型编程技术实现的,详细定义请参考/usr/include/c++/5/bits/basic_string.h头文件看起来很复杂,具体实现这里不关心,所以不再讨论。测试string类对象占用的内存空间通过下面的代码,可以测试string类对象占用的内存空间。//demo.cpp#include#includeintmain(intargc,charconst*argv[]){usingnamespacestd;strings15(15,'a');//字符串长度15strings16(16,'x');//字符串长度16cout<<"sizeof(string)="<(gdb)x/16x0xffffcdf4//The9-24bytesofthestringobjects15arecharacterarraysrepresentingdata0xffffcdf4:0x610x610x610x610x610x610x610x610xffffcdfc:0x610x610x610x610x610x610x610x00(gdb)x/wx&s16//打印变量s16的内存地址0xffffce04:0x0804fa10(gdb)x/6xw0xffffce04//打印string对象s16占用的24个字节内存数据0xffffce04:0x0804fa100x000000100x000000100x000000010xffffce14:0xffffced40xffffcedc(gdb)x/s0x0804fa10//string对象s16的1-4个字节是一个指向字符数据的指针0x804fa10:'x'(gdb)x/16x0x0804fa100x804fa10:0x780x780x780x780x780x780x780x780x804fa18:0x780x780x780x780x780x780x780x78(gdb)cContinuing.[Inferior1(process20982)exitednormally](gdb)qFromtheabovedebugging,itcanbeseenthatthememorystructureofthestringobjectisverysimilartothefollowingstructure:typedeflongintu32;structString{char*data_ptr;//pointertocharacterarray,occupying4bytesu32lengthin32-bitprograms;//Thelengthofthecharacterarray,whichoccupies4bytesin32-bitprogramchardata[16];//Arraythatcanhold15characters,occupies16bytes};1.1-4bytesofthestringobjectItisapointertocharacterdata2.The5-8bytesofthestringobjectisanintegervaluerepresentingthelengthofthecharacterdata.3.Themeaningofthe9-24bytesofthestringobjectchangesaccordingtothelengthofthecharacterdata.Ifthelengthofthecharacterarraycontainedinthestringobjectislessthan16,savethecharacterdatainthememoryoccupiedbythestringobjectitself;taketheabovestructureStringasanexample,savethecharacterdataindata.s15.data_ptr==&(s15.data[0]);如果字符串对象包含的字符数组长度大于等于16,则其字符数据位于可执行文件的数据区或分配到堆内存而不是栈内存;取上文structureString为例,字符数据不能存储在数据字段中。64位可执行程序中字符串对象的内存分配与32位程序非常相似,只是在64位程序中,指针对象占用8字节内存;通过动态调试,发现内存分配很像下面的结构:typedeflonglongintu64;structString{char*data_ptr;//指向字符数组的指针,在64位机器上占8字节u64length;//字符数组的长度,在64位机器上占8字节chardata[16];//可以容纳一个数组15个字符,占用16个字节};以上内容是两年多前的学习笔记,最近在如下环境测试,得到的结论与以上内容一致。操作系统:Ubuntu20.04。调试软件:GNUgdb(Ubuntu9.2-0ubuntu1~20.04)9.2.编译工具:g++(Ubuntu9.3.0-17ubuntu1~20.04)9.3.0。本文转载自微信公众号「记忆中的Golang」