c++ - 检测到堆损坏 | C++

标签 c++ heap-memory heap-corruption

运行此代码后,我收到“检测到堆损坏”消息:

uli& uli::operator =(char* n)
{
    char* buffer = new char[strlen(n)];

    char* p;
    int op;
    int coef;

    strcpy(buffer, n);

    while(*buffer)
    {
        op = strlen(buffer) - 5;
        p = (op >= 0) ? op+buffer : buffer;
        coef = atoi(p);

        if(coef > 65535)
            coef = atoi(++p);

        push(head, coef);
        *p = '\0';
    }

    delete buffer;       //  <- heap corruption detected

    return *this;
}

这是我调用方法的方式:

uli x;
x = "9876123";

“检测到堆损坏”是什么意思?

最佳答案

“堆损坏”通常意味着您写入未分配的内存,破坏了用于使内存分配器工作的数据结构。

可能还有更多问题,但我看到的第一个是在这一行:

strcpy(buffer, n);

这会将 strlen(n) + 1 字节写入 buffer,但是 buffer 只是 strlen(n) 字节长(额外字节是终止 \0。)写入该额外字节会导致未定义的行为,并且很可能会损坏堆。

关于c++ - 检测到堆损坏 | C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9551941/

相关文章:

c++ - MFC 程序中的堆损坏

c++ - 写入文件时出现堆损坏

c++ - 使用 C++ 编辑注册表

c++ - 查找十六进制字符串是 utf-8 还是 utf-16

c++ - C++ 中指向对象的指针——堆栈/堆上有什么?

java - 相同的程序,相同的 JVM,但在不同机器上的内存需求和执行时间却大不相同——为什么?

c++ - 具有可变返回类型的函数

python - C++ (STL map) 等效于 Python 的 setdefault 的方法

java - Android 中的堆转储和内存使用差异?

c++ - 检测到堆损坏 : after Normal block (#126)