加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

c – gcc/linux:CppuTest使用静态向量显示内存泄漏,误报?

发布时间:2020-12-13 19:23:27 所属栏目:Linux 来源:网络整理
导读:在xxxx.h文件中: struct dn_instance_pair{ std::string theDn; int theInstance;};typedef struct dn_instance_pair t_dn_inst_pair;struct table_rowid_type{ char theTable[101]; sqlite3_int64 theRowid; int operation;};// static class membersstati

在xxxx.h文件中:

struct dn_instance_pair
{
    std::string theDn;
    int theInstance;
};
typedef struct dn_instance_pair t_dn_inst_pair;

struct table_rowid_type
{
    char theTable[101];
    sqlite3_int64 theRowid;
    int operation;
};

// static class members
static vector

在xxxx.cpp中

// declaration of vectors.
// Included to this post only for completeness.
vector

这些向量在静态回调函数中处理,因此它们也必须是静态的.

在cpputest中,当尝试在这些向量中的任何一个中添加某些内容时,会发生故障:

Leak size: 8 Allocated at: 

添加到向量中的东西是自动变量,它发生在正常函数中:

t_dn_inst_pair thePair;
thePair.theDn = updated_dn;
thePair.theInstance = updated_instance;

在测试用例结束时清除向量:

xxxx::yyyy()->dninstList.clear();

(yyyy()返回指向单例xxxx对象的指针)

第http://blog.objectmentor.com/articles/2010/02/04/cpputest-recent-experiences页
讨论了同样的内存泄漏:

“This is a false positive. This is a one-time allocation and a
side-effect of C++ memory allocation and static initialization.”

所以我的问题是:
这种失败真的是假阳性吗?

br Esko

最佳答案
你和valgrind签过了吗?它会将“绝对丢失”的泄漏内存与“仍可访问”的内存区分开来.如果它是误报,它应该仍然可以访问(通过向量中的指针).

请记住,vector :: clear()只是破坏元素,它不会释放任何内存,因此capacity()将保持不变.

您可以执行交换技巧以强制向量释放其内存:

vector

这会创建一个临时(空)向量并将其与向量交换,因此向量的元素和已分配的内存将被转移到临时值,然后在语句结束时被销毁.

附:单身者很糟糕,不要使用它们,但是如果它是静态成员,你为什么要像yyyy() – > dninstList(即使用operator->)那样访问向量?您可以说xxxx :: dninstList或使其成为非静态成员并通过单例对象访问它(但不要忘记单身人员吮吸.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读