C++ 检测到堆损坏| C++;

C++ 检测到堆损坏| C++;,c++,heap,corruption,C++,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) ?

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

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;
}
“检测到堆损坏”是什么意思?

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

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

strcpy(buffer, n);

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

欢迎!请在网站允许的情况下接受答案。另外,不要错过Ates Goral的评论。如果使用
new[]
进行分配,则必须使用
delete[]
进行释放。您是否想过使用对象来处理内存。可能是std::string而不是char*。
strcpy(buffer, n);