以下代码从磁盘读取一个大对象集合(95G压缩对象,通过WriteObject流处理器解压缩),并将其内容打印为字符串。
object.cxx:
std::vector<char> ObjectHandler::GetObject(const std::string& path)
{
TFile *file = new TFile(path.c_str());
// If file was not found or empty
if (file->IsZombie()) {
cout << "The object was not found at " << path << endl;
}
// Get the AliCDBEntry from the root file
AliCDBEntry *entry = (AliCDBEntry*)file->Get("AliCDBEntry");
// Create an outcoming buffer
TBufferFile *buffer = new TBufferFile(TBuffer::kWrite);
// Stream and serialize the AliCDBEntry object to the buffer
buffer->WriteObject((const TObject*)entry);
// Obtain a pointer to the buffer
char *pointer = buffer->Buffer();
// Store the object to the referenced vector
std::vector<char> vector(pointer, pointer + buffer->Length());
// Release the open file
delete file;
delete buffer;
return vector;
}
main.cxx:
ObjectHandler objHandler;
boost::filesystem::path dataPath("/tmp");
boost::filesystem::recursive_directory_iterator endIterator;
if (boost::filesystem::exists(dataPath) && boost::filesystem::is_directory(dataPath)) {
for (static boost::filesystem::recursive_directory_iterator directoryIterator(dataPath); directoryIterator != endIterator;
++directoryIterator) {
if (boost::filesystem::is_regular_file(directoryIterator->status())) {
cout << directoryIterator->path().string() << endl;
std::vector<char> vector = objHandler.GetObject(directoryIterator->path().string());
cout << vector << endl;
}
}
}
1)按值调用是否正确实现此方法?我是否正在做其他副本,如果通过引用进行调用可以避免?
2)此代码泄漏,我怀疑 char *指针是否应该归咎于返回的 std :: vector em> ObjectHandler :: GetObject()方法。我已使用以下代码测试了实现:
struct sysinfo sys_info;
sysinfo (&sys_info);
cout << "Total: " << sys_info.totalram *(unsigned long long)sys_info.mem_unit / 1024 << " Free: " << sys_info.freeram *(unsigned long long)sys_info.mem_unit/ 1024 << endl;
并且自由ram不断减少,直到它达到0并且程序被杀死。
答案 0 :(得分:1)
&#34;内存泄漏&#34;是一个可以涵盖一些事物的术语;取决于你与谁交谈。 一个是没有匹配删除的新内容。 另一个经常被查看过的内存是仍在引用和范围内的内存,但只是没有使用或需要。
如果你不使用profiller,那么你无法确定你有哪些,但是因为你传递了一个大型载体,我们不知道是什么你做到了,你可能会做第二次,没有人会看到。