我使用 valgrind --leak-check=full 检查我的程序,发现了一个我不知道的泄漏:
==6072== 54 bytes in 2 blocks are possibly lost in loss record 15 of 28
==6072== at 0x4C2AF8E: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==6072== by 0x55B63B8: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==6072== by 0x55B7D94: char* std::string::_S_construct<char const*>(char const*, char const*, std::allocator<char> const&, std::forward_iterator_tag) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==6072== by 0x55B7E72: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==6072== by 0x4268ED: Writable::readString(std::istream*) (Writable.cpp:33)
这是我的代码片段:
#include "Writable.h"
Writable::Writable()
{
//ctor
}
Writable::~Writable()
{
//dtor
}
void Writable::writeString(ostream* ofs, string str){
int length = str.size()+1;
ofs->write((char*)&length, sizeof(length));
if (length > 1)
ofs->write(str.c_str(), length);
}
string Writable::readString(istream* ifs) {
int length = 0;
ifs->read((char*)&length, sizeof(length));
if(length > 1) {
char buf[length];
ifs->read(buf, length);
return string(buf);
}
return string("");
}
它指向“返回字符串(buf)”行。你能弄清楚泄漏是如何在那里完成的吗?
干杯