C ++堆损坏,但仅在单元测试项目中

问题描述 投票:1回答:1

我正在使用模板实现自定义堆栈。但是我遇到了一个问题,使我对内存安全性提出了质疑。正常使用时,析构函数可以正常工作,但是在进行单元测试时,它将触发堆破坏。特别是在预期会引发异常的测试上。

所有堆栈代码。

#pragma once
#include "StackOverflowException.h"
#include "StackEmptyException.h"

template <class T>
class Stack
{
public:
    const static int MAX_SIZE = 1000;

    Stack() : m_array(new T[MAX_SIZE]), m_size(0), m_top(0) {};
    Stack(const Stack<T>& _other)
    {
        m_array = new T[MAX_SIZE];
        for(auto i = 0; i < _other.size(); ++i)
        {
            m_array[i] = _other.m_array[i];
        }
        m_size = _other.size();
        m_top = _other.m_top;
    }

    ~Stack()
    {
        delete[] m_array;
    }

    void push(T _item)
    {
        if (m_size + 1 == MAX_SIZE + 1)
        {
            throw StackOverflowException();
        }
        m_array[++m_top] = _item;
        ++m_size;
    }

    T pop()
    {
        if(m_top != 0)
        {
            --m_size;
            T item =  m_array[m_top];
            --m_top;
            return item;
        }
        throw StackEmptyException();
    }

    T peek() const
    {
        if (m_size == 0) throw StackEmptyException();
        T item = m_array[m_top];
        return item;
    }

    bool empty() const
    {
        return m_size == 0;
    }

    size_t size() const
    {
        return m_size;
    }
private:
    T* m_array;
    size_t m_size;
    int m_top;
};

导致堆损坏的单元测试。


        TEST_METHOD(CustomStackPopException)
        {
            Stack<int> stack;
            Assert::ExpectException<StackEmptyException>([&] { stack.pop(); });
        }

        TEST_METHOD(CustomStackPeekException)
        {
            Stack<int> stack;
            Assert::ExpectException<StackEmptyException>([&] { int a = stack.peek(); });
        }

        TEST_METHOD(CustomStackOverflowException)
        {
            Stack<int> stack;
            const auto functor = [&]
            {
                for(auto i = 0; i <= Stack<int>::MAX_SIZE; ++i)
                {
                    stack.push(i);
                }
            };
            Assert::ExpectException<StackOverflowException>(functor);
        }

当到达那些测试中的第一个时,它将抛出一个弹出警告,说:

HEAP CORRUPTION DETECTED: after Normal block(#279) at 0x0000020298CBC60.
CRT detected that the application wrote to memory after end of heap buffer.

我尝试在堆上制作堆栈对象,但这会导致相同的错误。

c++ memory-management heap-corruption
1个回答
0
投票

此成员函数

void push(T _item)
{
    if (m_size + 1 == MAX_SIZE + 1)
    {
        throw StackOverflowException();
    }
    m_array[++m_top] = _item;
    ++m_size;
}

已经不正确。假设MAX_SIZE等于1且m_size等于0。在这种情况下,m_size +1不等于MAX_SIZE +1且有写法。

    m_array[1] = _item;

在分配的数组之外。

© www.soinside.com 2019 - 2024. All rights reserved.