1

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); //+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.

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

oh i hate myself. Thank you very much, that worked, will mark as answer asap.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.