HEAP CORRUPTION DETECTED: after Normal block

I am trying to define on my own the string class in C++ just for practice and when defining an append function I get the following error:

HEAP CORRUPTION DETECTED: after Normal block CRT detected that the application wrote to memory after end of heap buffer.

The break is when I try to deallocate memory in "delete[] aPtr" Here is my code:

Private members: int len, cap; char *aPtr;

String::String()  //default constructor
{
len = 0;
cap = 1;
aPtr = new char[1];
aPtr[0] = '';
}


String::String(const String &original) //copy constructor
{
if (cap < original.len)
{
    char *t;

    cap*=2;
    len = original.len;
    t = new char[cap];

    for (int i = 0;i < len + 1;i++) //copy
    {
        t[i] = original.aPtr[i];
    }

    delete[] aPtr;

    aPtr = t;
}

else
{
    len = original.len;

    for (int i = 0;i < len + 1;i++) //copy
    {
        aPtr[i] = original.aPtr[i];
    }
}

}

String & String::operator=(const String &original)  // = overload
{
if (*this != original) //Check if string = string
{
    if (cap < original.len)
    {
        char *t;

        len = original.len;
        cap *= 2;

        t = new char[cap];

        for (int i = 0;i < len + 1;i++) //copy
        {
            t[i] = original.aPtr[i];
        }

        delete[] aPtr;

        aPtr = t;
    }

    else 
    {
        len = original.len;

        for (int i = 0;i < len + 1;i++) //copy
        {
            aPtr[i] = original.aPtr[i];
        }
    }
}

return *this;
}

void String::append(const String &str)
{
char *temp;

int newLen = len + str.len;

if (cap < newLen + 1)
{
    cap = 2 * newLen;

    temp = new char[cap];

    for (int i = 0;i < len;i++)
    {
        temp[i] = aPtr[i];
    }

    for (int i = 0; i < str.len + 1;i++)
    {
        temp[len + i] = str.aPtr[i];
    }

    delete [] aPtr;

    aPtr = temp;
    len = newLen;
}

else 
{
    for (int i = 0; i < str.len + 1;i++)
    {
        aPtr[len + i] = str.aPtr[i];
    }
}

}

Any help is appreciated!

链接地址: http://www.djcxy.com/p/82336.html

上一篇: 堆腐败c ++函数返回一个表指针

下一篇: HEAP CORRUPTION DETECTED:after Normal block