Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

heap corruption detected | C++

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 ?

like image 365
Jonas Avatar asked Mar 04 '12 02:03

Jonas


1 Answers

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

like image 121
Ernest Friedman-Hill Avatar answered Oct 17 '22 15:10

Ernest Friedman-Hill