Esk*_*nen 6 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;
Run Code Online (Sandbox Code Playgroud)
在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;
Run Code Online (Sandbox Code Playgroud)
这些向量在静态回调函数中处理,因此它们也必须是静态的.
在cpputest中,当尝试在这些向量中的任何一个中添加某些内容时,会发生故障:
Leak size: 8 Allocated at: <unknown> and line: 0. Type: "new" Content: "<\ufffdP@"
Run Code Online (Sandbox Code Playgroud)
添加到向量中的东西是自动变量,它发生在正常函数中:
t_dn_inst_pair thePair;
thePair.theDn = updated_dn;
thePair.theInstance = updated_instance;
Run Code Online (Sandbox Code Playgroud)
在测试用例结束时清除向量:
xxxx::yyyy()->dninstList.clear();
Run Code Online (Sandbox Code Playgroud)
(yyyy()返回指向单例xxxx对象的指针)
页面http://blog.objectmentor.com/articles/2010/02/04/cpputest-recent-experiences 讨论了相同类型的内存泄漏:
"这是误报.这是一次性分配和C++内存分配和静态初始化的副作用."
所以我的问题是:这种失败真的是假阳性吗?
br Esko
你用valgrind检查过吗?它将区分“肯定丢失”的泄漏内存和“仍然可以访问”的内存。如果它是误报,它应该仍然可以访问(通过向量中的指针。)
请记住,vector::clear()只是销毁元素,它不会释放任何内存,因此capacity()将保持不变。
您可以执行交换技巧来强制向量释放其内存:
vector<t_dn_inst_pair>().swap(xxxx::yyyy()->dninstList);
Run Code Online (Sandbox Code Playgroud)
这会创建一个临时(空)向量并将其与您的向量交换,因此您的向量元素和分配的内存将被转移到临时向量,然后在语句结束时销毁。
PS Singletons 很糟糕,不要使用它们,但是如果它是静态成员,为什么要访问向量yyyy()->dninstList(即使用operator->)?您可以说xxxx::dninstList或使其成为非静态成员并通过单例对象访问它(但不要忘记单例很糟糕。)