我在代码上收到“HEAP CORRUPTION DETECTRD: after Normal Block(#72)”错误。这是什么意思?
我不断收到“CRT 检测到应用程序在堆缓冲区结束后写入内存。” Visual Studio 2019 中的代码出错并返回 3。但是使用 gcc 编译时相同的代码没有错误并返回 0。经过数小时的搜索,我没有找到解决方案。
#include <iostream>
class Vector
{
public:
Vector();
~Vector();
std::size_t size() const { return m_end - m_begin; }
std::size_t capacity() const { return m_capacity - m_begin; }
int* begin() const { return m_begin; }
int* end() const { return m_end; }
void push_back(const int& );
Vector(const Vector& obj)
{
int* rhs_beg = obj.m_begin;
int* new_beg = alloc.allocate(size());
int* temp_new_beg = new_beg;
for (std::size_t it = 0; it != size(); ++it)
{
alloc.construct(temp_new_beg++, *rhs_beg++);
}
m_begin = new_beg;
m_capacity = m_end = temp_new_beg;
}
private:
std::allocator<int> alloc;
int* m_begin, *m_end, *m_capacity;
void chk_n_alloc();
void allocate();
void free();
};
Vector::Vector()
:m_begin(nullptr), m_end(nullptr), m_capacity(nullptr)
{
}
void Vector::free()
{
for (auto it = m_end; it != m_begin;)
alloc.destroy(--it);
alloc.deallocate(m_begin, size());
}
void Vector::chk_n_alloc()
{
if (size() == capacity())
allocate();
}
void Vector::allocate()
{
std::size_t n_size;
int* beg = nullptr;
if (!size())
beg = alloc.allocate(1);
else
beg = alloc.allocate(size() * 2);
int* new_begin = beg;
int* t_begin = m_begin;
for (int i = 0; i != size(); ++i)
alloc.construct(new_begin++, std::move(*t_begin++));
free();
m_begin = beg;
m_end = new_begin;
n_size = size() * 2;
m_capacity = m_begin + n_size;
}
void Vector::push_back(const int& x)
{
chk_n_alloc();
alloc.construct(m_end++, x);
}
Vector::~Vector()
{
free();
}
int main()
{
Vector v;
v.push_back(12);
v.push_back(10);
}
仅当我多次尝试调用 Vector::push_back() 时才会发生错误。这是错误代码:“HEAP CORRUPTION DETECTRD:在 Normal Block(#72) 之后。”
最佳答案
这意味着您的程序正在写入不应该写入的内存并覆盖运行时用于管理堆的管理内存。
常见原因有:
- 在分配的 block 之外写入。例如。
new[]
一个大小为 4 的数组,并写入第 5 或第 6(等)项。负偏移量也可以。 - 释放内存并在之后写入。
- 取消引用(并写入)指向随机内存位置的未初始化指针
在您的代码中,我会仔细检查您访问的内存、访问时间以及当时是否安全。您可以使用调试器来跟踪您的代码在做什么,或者使用地址清理器构建/运行,这会提供有关此类错误的更多有意义的信息。
关于c++ - C++ 中的 "HEAP CORRUPTION"错误是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58473050/