heap corruption detected | C++
Asked Answered
A

1

11

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

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;
}

This is how I call the method:

uli x;
x = "9876123";

What does "heap corruption detected" mean ?

Antinomy answered 4/3, 2012 at 2:58 Comment(1)
Have you though of using an object to handle the memory. Maybe a std::string instead of a char*.Vanny
C
20

"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:

strcpy(buffer, n);

This will write strlen(n) + 1 bytes to buffer, but buffer is 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.

Charland answered 4/3, 2012 at 3:0 Comment(1)
Also, don't miss Ates Goral's comment. If you allocate with new[], you must free with delete[].Autogiro

© 2022 - 2024 — McMap. All rights reserved.