简体   繁体   English

Valgrind内存泄漏

[英]Valgrind memory leak

Record* MyClass::get_record (int id)
{
    Record* rec = new Record();
    Record* compressed_rec;

    /* ... code that gets compressed_rec into memory ... */

    compressed_rec->decompress(rec);

    return rec;
}

This function is always used like this: 始终按以下方式使用此功能:

Record* rec = my_class_instance.get_record (id);
show_contents_of(rec);
delete rec;

valgrind says that i'm leaking memory on the first line ( Record* rec = new Record(); ). valgrind说我在第一行泄漏内存( Record* rec = new Record(); )。 Why? 为什么?

valgrind says that i'm leaking memory on the first line (Record* rec = new Record();). valgrind说我在第一行泄漏内存(Record * rec = new Record();)。 Why? 为什么?

Does it show the Record itself is being leaked, or something else allocated inside Record::Record ? 它是否表明Record本身正在泄漏,或在Record::Record内部分配了其他内容?

If the former, either some return path from MyClass::get_record leaks it, or the caller leaks it. 如果是前者,则MyClass::get_record某些返回路径会将其泄漏,或者调用者将其泄漏。 Switching to use a smart pointer would fix both cases: 切换为使用智能指针将解决两种情况:

std::unique_ptr<Record> MyClass::get_record (int id)
{
    std::unique_ptr<Record> rec(new Record());
    ...
    return rec;
}

If it's the latter case, that either means the whole Record is being leaked (see above), or its destructor is buggy. 如果是后一种情况,则意味着整个Record正在泄漏(请参见上文),或者其析构函数是错误的。 Again, try keeping any dynamically allocated members in smart pointers. 同样,尝试将任何动态分配的成员保留在智能指针中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM