开发者

Deleting char pointer array

I want to delete a char * array, which should be simple right? char * = new char[length]; then use delete[] char;?

Also, I am unable to use std::string for this exercise.

I'm getting this error:

HEAP CORRUPTION DETECTED: after Normal block (#137) 0x00794B50.

CRT detected that the application wrote to memory after end of heap buffer.

Here is my code:

class myClass
{
    char * myString;
    ...
public:
    myClass::myClass( const char * tempStr);
};

myClass::myClass( const char * tempStr)
{
    int length = strlen(tempStr);
    myString = new char(length + 1);开发者_JAVA技巧 //+1 for null char
    strcpy(myString, tempStr);
    myString[length] = '\0';
    delete[] myString; //error occurs here
}

Now, I know, this code is completely impractical, however it still throws the same error that I am trying to solve so if we can solve this then I should be merrily on my way. From what I've read this should be OK? I'll reiterate, for this exercise I cannot use std::string.


You messed the brackets up. It should be:

myString = new char[length + 1];

Square brackets will create an array. Normal brackets will allocate only one with whatever constructor takes that one operand.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜