8

在 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;

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

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

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

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

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 讨论了相同类型的内存泄漏:

“这是误报。这是一次性分配,是 C++ 内存分配和静态初始化的副作用。”

所以我的问题是:这种失败真的是误报吗?

br 爱斯科

4

1 回答 1

5

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

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

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

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

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

P.S. Singletons suck, don't use them, but why do you access the vector as yyyy()->dninstList (i.e. using operator->) if it's a static member? You could either say xxxx::dninstList or make it a non-static member and access it via the singleton object (but don't forget that singletons suck.)

于 2012-05-30T09:37:19.810 回答