I have a simple program:
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
string read0() {
int length = 4;
char *cstr = new char[length];
string str(cstr);
delete[] cstr;
return str;
}
string read1() {
int length = 4;
char cstr[length];
memset(cstr, '-', 4);
string str(cstr);
return str;
}
string read2() {
const char* cstr = "abcd";
string str(cstr);
return str;
}
In all 3 functions above, for constructing a string, they call basic_string( const CharT* s, const Allocator& alloc = Allocator()
. When I use valgrind/massif to check the heap usage, function read0 only uses 4 bytes (from new
), but read1 and read2 both use 29 bytes.
Here's some detail output of massif:
For read0:
16.67% (4B) (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
->16.67% (4B) 0x400A0B: read0() (main.cpp:10)
->16.67% (4B) 0x400BC8: main (main.cpp:40)
For read1 and read2:
72.50% (29B) (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
->72.50% (29B) 0x4EE93B7: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
->72.50% (29B) 0x4EEAD93: char* std::string::_S_construct(char const*, char const*, std::allocator const&, std::forward_iterator_tag) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
->72.50% (29B) 0x4EEAE71: std::basic_string, std::allocator >::basic_string(char const*, std::allocator const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
->72.50% (29B) 0x400B81: read2() (main.cpp:34)
->72.50% (29B) 0x400BC8: main (main.cpp:40)
What causes this difference?