谷歌测试中的RAII内存损坏
RAII memory corruption in Google Test
我已经为c指针实现了一个自动删除器。代码在测试程序中工作,但当我在Google test中使用代码时,奇怪的事情发生了。我不明白为什么。我写的是未定义的行为吗?或者Google Test会以某种方式干扰?
下面的代码,如果宏ASSERT_THAT
被注释掉,打印:
i1 = 0x8050cf0
i2 = 0x8050d00
got: 0x8050cf0
got: 0x8050d00
go delete: 0x8050cf0
go delete: 0x8050d00
创建了两个指针,守卫得到这些指针,然后删除它们。到目前为止完全符合要求。
如果宏是活动的,结果是:
i1 = 0x8054cf0
i2 = 0x8054d00
got: 0x8054cf0
got: 0x8054d00
go delete: 0x8054c01
由于某种原因,代码删除了另一个指针,然后删除了一个指针。我完全糊涂了。你能帮忙发现问题吗?
#include <iostream>
#include <gmock/gmock.h>
using namespace testing;
class Scope_Guard {
public:
Scope_Guard(std::initializer_list<int*> vals)
: vals_(vals)
{
for (auto ptr: vals_) {
std::cerr << "got: " << ptr << std::endl;
}
}
~Scope_Guard() {
for (auto ptr: vals_) {
std::cerr << "go delete: " << ptr << std::endl;
delete ptr;
}
}
Scope_Guard(Scope_Guard const& rhs) = delete;
Scope_Guard& operator=(Scope_Guard rhs) = delete;
private:
std::initializer_list<int*> vals_;
};
TEST(Memory, GuardWorksInt) {
int* i1 = new int(1);
int* i2 = new int(2);
std::cerr << "i1 = " << i1 << std::endl;
std::cerr << "i2 = " << i2 << std::endl;
Scope_Guard g{i1, i2};
ASSERT_THAT(1, Eq(1)); // (*)
}
int main(int argc, char** argv) {
InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
未定义行为:
你正在从构造函数参数复制一个std::initializer_list
到一个类成员。
复制std::initializer_list
并不复制其底层元素。因此,离开构造函数后,不能保证vals_
包含任何有效的内容。
为成员使用std::vector
,并从初始化列表中构造它。
我不确定你对这个守卫的意图,但可能更容易使用std::unique_ptr
。
相关文章:
- 如何针对特定情况调试和修复此双自由内存损坏问题
- 正在调试 malloc():新内存损坏
- 仅特定内核计数上的 MPI 内存损坏
- C++程序错误:malloc():内存损坏
- 调用std::函数成员时内存损坏
- C++ 内存损坏检测
- 由于标头中的 #define 不匹配而导致内存损坏
- C STD ::线程中的种族状况或内存损坏
- malloc()内存损坏仅通过为特定数量编写int数组
- 字符串标记化期间的内存损坏
- 从检测到 glibc 正常退出 - malloc():内存损坏
- 放置在外部 DLL 中的类中的字符串数据的内存损坏
- std :: string ::擦除会导致内存损坏
- 编译器如何检测内存损坏
- mix_playMusic导致内存损坏
- 在使用新操作员和C 中的结构的调用构造函数时,获得内存损坏(Malloc)
- 两个内联程序集调用与一个内联程序集调用中的内存损坏?
- 如何调试不确定内存损坏?
- 增强Dijkstra代码会导致片段内存损坏
- 内存损坏从vb.net调用c dll