Heap Damage Detected | C ++

I got 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 discovery mean?

+7
source share
1 answer

“Heap corruption” usually means that you wrote to unallocated memory, damaging the data structures used to operate the memory allocator.

There may be more problems, but the first of them I see in this line:

 strcpy(buffer, n); 

This will write strlen(n) + 1 bytes to buffer , but buffer is only strlen(n) bytes (the extra byte is the final \0 ) Writing this extra byte leads to undefined behavior and can damage the heap.

+14
source

All Articles