-4
以下代码是从磁盘读取大对象集合(通过WriteObject流媒体压缩的对象的95G压缩对象)并将其内容打印为字符串。C++ char * + std ::向量内存泄漏
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)该代码被泄漏,我怀疑任字符*指针的错,或实际的std ::矢量由所述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并且程序被终止。
如果你觉得你的程序泄漏了内存,那么你应该尝试一些调试工具来帮助跟踪,比如[Massif](http://valgrind.org/info/tools.html#massif)。请注意,使用这些工具,您的程序运行速度会相当慢。 –
'//从根文件获取AliCDBEntry AliCDBEntry *条目=(AliCDBEntry *)文件 - >获取(“AliCDBEntry”);'? – kfsone
每个问题一个问题。 –