代码崩溃,但在与Valgrind一起运行时可以运行,但是Valgrind报告错误

时间:2018-10-27 09:23:29

标签: c++ arrays new-operator delete-operator

我有一个要管理的对象数组池。池根据需要无限期增加,直到程序结束。当我尝试调整池大小时,它在前三个调整大小操作中幸免,然后在删除旧数组时在第四个崩溃。池的大小很小,并且内存没有用完。

typedef measure* measure_ptr;

const uint32_t PoolIncrementSize = 50;

void CreatePool()
{
    if(measurePool != nullptr)
    {
        throw std::runtime_error("Pool has already been initialized!");
    }
    poolSize = PoolIncrementSize;
    measure_ptr* createdPool = new measure_ptr[poolSize];
    for(uint32_t i = 0; i < poolSize; i++)
    {
        createdPool[i] = nullptr;
    }
    measurePool = createdPool;
}

void ResizePool()
{
    poolSize += PoolIncrementSize;
    measure_ptr* createdPool = new measure_ptr[poolSize];
    std::memcpy(createdPool, measurePool, (size_t)(poolCursorPosition * sizeof(measure_ptr)));
    delete[] measurePool;
    for(uint32_t i = poolCursorPosition; i < poolSize; i++)
    {
        createdPool[i] = nullptr;
    }
    measurePool = createdPool;
}

// When stuff gets returned to pool this happens
if(poolCursorPosition == poolSize)
    ResizePool();

程序在我删除旧数组的那一行上的第三次调整大小操作(大小从150-> 200增加)时崩溃。

与Valgrind一起运行时,程序不会崩溃并且运行正常,但是Valgrind会报告Address <some memory address> is 8 bytes after a block of size <correct amount of bytes> allocated的新数组创建以及我从池中获取元素并放入{{1 }}返回数组到nullptr的位置,它报告poolCursorPosition

为什么在不运行Valgrind的情况下代码不起作用?如何使Valgrind错误消失?

编辑:

添加访问池的代码:

Invalid write of size 8

0 个答案:

没有答案