4 ms·
> "foofoo" takes up twice as much space in memory as "foo". Not in the imaginary language you keep talking about as "C/C++".
by zabzonk 6y ago
> "foofoo" takes up twice as much space in memory as "foo".
Not in the imaginary language you keep talking about as "C/C++".
- pornel 6y agoRight, in case they're heap allocated, the worst-case alignment requirement of malloc, as well as free() without a size is likely to force implementations to round it up to at least 8 or 16 bytes for both.
- ncmncm 6y agoNo. The result of std::string("foo") is exactly the same size as of std::string("foofoo"). They take up exactly the same number of bytes in the free store, on the stack, in a hash table, what have you. When the string is very long, it occupies two stretches of storage, one exactly the same size as std::string("foo"), plus another stretch big enough for the long sequence plus whatever overhead heap allocation adds. But that is different from the examples given. For the cases cited, there is no indirection of any kind. The bytes are right there in the std::string object.
- pornel 6y agoWe just interpret "space in memory" at different levels of indirection. If you try to create std::string("verylong…") with more characters than you have memory, you run out of memory, so it "takes up space in memory", even though std::string has the same size as always. Bonus fact: *"foo" and *"foofoo" in Rust dereference to 3 bytes and 6 bytes, respectively. It's neither a pointer nor the first char.
- zabzonk 6y agoI actually (and pedantically, I'm afraid) meant that neither in C or C++ is it true that "foofoo" takes up double the size of "foo" - both will have a zero character at the end. The sizeof operator when applied to each will also return values that indicate that one is not double of the value of the other.
- brundolf 6y agoI was approximating for the sake of demonstration (as stated in the note that followed)
- Someone 6y agoThat’s disingenuous. That quote is _immediately_ followed by a note > Technically there will be a tiny amount of extra data, like a length, so it won't be precisely twice the size. But it's close enough for our purposes. Also, nitpicking, those two strings _can_ take up the same amount of memory due to short string optimization (https://joellaity.com/2020/01/31/string.html https://joellaity.com/2020/01/31/string.html shows that libc++ uses 24 bytes for strings up to 22 bytes long) or (for implementations that don’t do SSO) due to granularity of heap allocations.