why do i get heap corruption when trying to delete the char array.
The code below is in “main()”
case 'r':
char *StrTReverse = new char;
std::cout << "Enter a string: " << std::endl;
std::cin >> StrTReverse;
std::cout << "String reversed: " << ReverseString(StrTReverse) << std::endl;
system("pause");
delete[] StrTReverse; <- Here the is the crash
break;
below is the ReverseString function
char* ReverseString(char string[])
{
int StringLength = std::strlen(string);
char *NewString = new char[StringLength];
for (int i = 0, j = StringLength-1; i < StringLength;i++,j--)
{
NewString[i] = string[j];
}
NewString[StringLength] = '\0';
return NewString;
};
I cant understand why this is happening. I am new to c++ so please take that in mind.
thanks for any help 🙂
You dont’t allocate an array so dont call
delete[]calldeleteReplace
with
The rule is call
deleteon address returned bynew&call
delete []on address returned bynew [].