在测试中使用unique_ptr时指针错误无效

Invalid pointer error when using unique_ptr in tests

本文关键字:ptr 指针 错误 无效 unique 测试      更新时间:2023-10-16

我有一个方法,它将std::unique_ptr<uint8_t[]>作为输入并对其进行处理。在我的单元测试中,

以下是我创建和初始化此参数的方法:(在堆栈上(

uint8_t testBytes[] = {1, 2, 3, 4};
std::unique_ptr<uint8_t[]> testBytesPtr = std::make_unique<uint8_t[]>(4);
testBytesPtr.reset(testBytes);

它被传递给方法,如下所示:

myClass.processData(std::move(testBytesPtr));

在单元测试结束时,我收到以下错误消息:

free((: 无效指针: 0xbed6b8c0


以下是我的单元测试的样子:

#include "gtest.h"
#include "gmock.h" // for some deps
//...
TEST(MyClassUnittests, test1) {
    // Initializing the byte array.
    uint8_t testBytes[] = {1, 2, 3, 4};
    std::unique_ptr<uint8_t[]> testBytesPtr = std::make_unique<uint8_t[]>(4);
    testBytesPtr.reset(testBytes);
    EXPECT_TRUE(myClass.processData(std::move(testBytestPtr));
}

我还应该注意,如果在上初始化testBytes(例如,uint8_t* testBytes = new uint8_t() (,错误消息变为

双重释放或损坏(快速顶部(:0xb75c1e18

任何帮助将不胜感激。

delete []不是

new []-ed的东西,也不是你拥有的东西,是严重禁忌的。

请看这些行:

uint8_t testBytes[] = {1, 2, 3, 4};
std::unique_ptr<uint8_t[]> testBytesPtr = std::make_unique<uint8_t[]>(4);
testBytesPtr.reset(testBytes);

删除不相关的临时动态分配离开:

uint8_t testBytes[] = {1, 2, 3, 4};
std::unique_ptr<uint8_t[]> testBytesPtr(testBytes);

这会导致 dtor 启动时出现未定义的行为。

诚然,你移动std::unique_ptr一次,但这只会改变爆炸发生的确切点。

考虑到您要测试的函数,请尝试以下操作以获取正确分配的测试数据副本:

uint8_t testBytes[] = {1, 2, 3, 4};
auto testBytesPtr = std::make_unique<uint8_t[]>(std::size(testBytes));
std::copy(std::begin(testBytes), std::end(testBytes), &testBytesPtr[0]);