Heap Corruption Detected when trying to delete an object (C++)

1.3k views Asked by At

I'm having problems with deleting an object at the end of my program. This is for a C++ course so we aren't allowed to use the string class (yet). I have a Weapon class that generates a name for a weapon, this name is instantiated with char* result = new char[len] which is then returned to the constructor. In the destructor I remove the name object with delete[] this->name.

Problem:

When I run my program, everything runs fine until the program comes to the deletion part of the program. Then I get this error message:

Debug Error!

Program: ... path to program ...

HEAP CORRUPTION DETECTED: after Normal block (#198) at 0x0100B918. CRT detected that the application wrote to memory after end of heap buffer.

(Press Retry to debug the application)

I have tried replacing delete with delete[] and vice versa, and it makes no difference.

Can anyone spot where I want wrong?

main.cpp:

int _tmain(int argc, _TCHAR* argv[]) {

    // ... code ...

    Weapon* weapon = new Weapon();

    // ... code ...

    delete weapon;

}

Weapon.cpp:

Weapon::Weapon() {
    this->name = this->generateName();
    // more properties...
}

Weapon::~Weapon() {
    delete[] this->name;
    this->name = nullptr;
}

char* Weapon::generateName() {
    int pr, tp, su; // random variables for picking prefix, type and suffix

    const char *prefix[10] = { // ... a bunch of names ... };
    const char *type[10] = { // ... a bunch of names ... };
    const char *suffix[10] = { // ... a bunch of names ... };

    pr = rand() % 9;
    tp = rand() % 9;
    su = rand() % 9;

    int len = strlen(prefix[pr]) + strlen(type[tp]) + strlen(suffix[su]) + 1;
    char *result = new char[len]();
    strcpy(result, prefix[pr]);
    strcat(result, " ");
    strcat(result, type[tp]);
    strcat(result, " ");
    strcat(result, suffix[su]);

    return result;
}
1

There are 1 answers

3
Sander De Dycker On BEST ANSWER

You forgot to allocate room in the string for the spaces :

int len = strlen(prefix[pr]) + strlen(type[tp]) + strlen(suffix[su]) + 1;

should be :

int len = strlen(prefix[pr]) + 1 + strlen(type[tp]) + 1 + strlen(suffix[su]) + 1;

The two extra characters would have overwritten memory beyond the allocated block, which accounts for the detected heap corruption.