Update: The following problem appears to depend on the -fwhole-program
option.
I've been playing around a bit with memory allocation, and I encountered a small mystery: In GCC (4.6), how does std::string
allocate its memory [edit]when I compile with -fwhole-program
[/]?
Have this following test program:
#include <new>
#include <string>
#include <iostream>
#include <cstdlib>
void * operator new(std::size_t n) throw(std::bad_alloc)
{
void * const p = std::malloc(n);
if (p == NULL) throw std::bad_alloc();
std::cerr << "new() requests " << n << " bytes, allocated at " << p << ".\n";
return p;
}
void operator delete(void * p) noexcept
{
std::cerr << "delete() at " << p << ".\n";
std::free(p);
}
int main()
{
std::string s = "Hello world.";
}
When I use any other dynamic container (which uses std::allocator<T>
), the allocator uses ::operator new
, and so I see the debug messages happily. However, with std::string
, I see nothing at all. I'm sure that dynamic allocation happens, though, as I can confirm with valgrind (13 plus string length bytes are allocated). I went through several source files and the standard, and I'm pretty sure that the template is std::basic_string<T, std::char_traits<T>, std::allocator<T>>
, so I'm at a loss why I don't see the messages from my replaced allocation functions.
Can anyone shed any light on this conundrum? What do I do to track string allocations? Also, could anyone run this through some other compiler and see if it produces any output?
(For example: if I add std::map<int, int> m { { 0, 1 } };
, I have output new() requests 24 bytes, allocated at 0x8d53028
etc.)
The standard library string functions allocate a smallish work buffer. If more space is needed, then the library reallocates to a larger buffer. It's just as simple as it sounds.
@user1145902: They are stored in memory like in an array, but that memory is not allocated in the stack (or wherever the string object is), but rather in a dynamically allocated buffer.
Inside every std::string is a dynamically allocated array of char .
clang / Linux / x86 / libc++ : 12 bytes.
Looking at the output of g++ ... -S
with / without -fwhole-program
it appears that the whole custom new/delete operators aren't emitted at all when using fwhole-program
.
I'm starting to suspect we're looking at a bug here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With