Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does std::string allocate memory in GCC with -fwhole-program?

Tags:

c++

gcc

c++11

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.)

like image 621
Kerrek SB Avatar asked Oct 02 '11 21:10

Kerrek SB


People also ask

How does std::string allocate memory?

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.

How are C++ strings stored in memory?

@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.

Is std::string dynamically allocated?

Inside every std::string is a dynamically allocated array of char .

How much memory is allocated to a string C++?

clang / Linux / x86 / libc++ : 12 bytes.


1 Answers

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.

like image 183
sehe Avatar answered Oct 15 '22 22:10

sehe