c++ - gcc/linux : CppuTest shows memory leak using static vectors, 误报?

标签 c++ linux gcc memory-leaks cpputest

在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<t_dn_inst_pair> dninstList;
static vector<t_table_rowid_type> tablerowidList;

在 xxxx.cpp 中

// declaration of vectors.
// Included to this post only for completeness.
vector<t_dn_inst_pair> xxxx::dninstList;
vector<t_table_rowid_type> xxxx::tablerowidList;

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

在 cpputest 中,当试图在这些 vector 中的任何一个中添加一些东西时,都会发生失败:

Leak size: 8 Allocated at: <unknown> and line: 0. Type: "new" Content: "<\ufffdP@"

添加到 vector 中的东西是自动变量,它发生在一个普通函数中:

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

vector 在测试用例结束时被清除:

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 艾司科

最佳答案

你检查过 valgrind 了吗?它将区分“肯定丢失”的泄漏内存和“仍可访问”的内存。如果它是误报,它应该仍然可以访问(通过 vector 中的指针。)

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

您可以使用交换技巧来强制 vector 释放其内存:

vector<t_dn_inst_pair>().swap(xxxx::yyyy()->dninstList);

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

附言单例很糟糕,不要使用它们,但是如果它是静态成员,为什么要将 vector 作为 yyyy()->dninstList(即使用 operator->)访问?您可以说 xxxx::dninstList 或使其成为非静态成员并通过单例对象访问它(但不要忘记单例很糟糕。)

关于c++ - gcc/linux : CppuTest shows memory leak using static vectors, 误报?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10812306/

相关文章:

c++ - 使用原始套接字 (c++)

c++ - 用不同的颜色和强度照亮物体

node.js - Node -bash :/usr/sbin/node: No such file or directory

linux - 如何打开一个新的终端窗口并从 shell 脚本在那里做事?

c - "Undefined symbols for architecture x86_64:"在c中是什么意思?

c++ - std::vector operator==: 值或引用比较?

java - 读取外部属性文件 Java/Linux

c - 我编码不正确吗?

python - 调试错误 "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

c++ - 无法使用 VeriFinger 保存处理过的指纹图像