检测到堆损坏| C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9551941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:58:28  来源:igfitidea点击:

heap corruption detected | C++

c++heapcorruption

提问by Jonas

I get this "heap corruption detected" message after running this code :

heap corruption detected运行此代码后,我收到此“ ”消息:

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 = '
uli x;
x = "9876123";
'; } delete buffer; // <- heap corruption detected return *this; }

This is how I call the method:

这就是我调用该方法的方式:

strcpy(buffer, n);

What does "heap corruption detected" mean ?

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

回答by Ernest Friedman-Hill

"Heap corruption" generally means you wrote into unallocated memory, damaging the data structures used to make the memory allocator work.

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

There may be more problems, but the first one I see is on this line:

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

##代码##

This will write strlen(n) + 1bytes to buffer, but bufferis only strlen(n)bytes long (the extra byte is the terminating \0.) Writing that extra byte results in undefined behavior, and may well corrupt the heap.

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