开发者

memory allocation for array of strings

开发者 https://www.devze.com 2023-04-10 18:45 出处:网络
As far as I know arrays are allocated statically but strings are dynamic as their length frequently changes during runtime.

As far as I know arrays are allocated statically but strings are dynamic as their length frequently changes during runtime.

What happens when I define an array like this:

std::string array[] = {"abc", "defghi", "jk", "lmnop", "qrstuvwxyz"};?

开发者_如何转开发Is there a limited amount of memory allocated for every string? Or is the array allocated dynamically?


Don't overthink things. When you say T x[N];, you declare an automatic (i.e. scope-local) array. This is very similar to just declaring T x1;, T x2;, ..., T xN;. An instance of std::string always occupies the same, small size in its declaration context (e.g. on the stack); it is only the memory which it manages (by default on the free store) that is dynamic.

Note that when you write std::string s("Hello"); in your code, then the string literal (which is passed to the constructor) is of course stored in your program binary somewhere, and it gets loaded into the program memory (usually a read-only data segment). So if you really just need to read those strings (as opposed to, say, modify them), then you might as well just declare an array of char pointers and save some memory:

const char * strings[] = { "Hello", "World", "!" };   // just one copy in r/o memory


The Literal strings are stored in the data segment of the binary.

Edit:

Good point in the comment by ildjarn. The std::strings are created by copy constructor in the arrays. Where they are stored is implementation dependent. Some implementation store small strings (less than 32 chars) inline in an array. Others will allocate from the std::allocator which is typically malloc-ed from the heap.


In this case the compiler places those literals in the .data section of your ELF binary. So in this case they are allocated statically in the executable (or library) file that you create.

The .data section is usually reserved for compile time constants that aren't just hardcoded into the assembly instructions. As you can see it's much cheaper to simply save an address to the string than to put it everywhere it is used (as is done by some integers and defined macros).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号