-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
每個問題一個問題。 –