Can anyone help me, why I’m getting an error message while trying to free the allocated memory: Heap corruption detected. CTR detected the application wrote the memory after end of heap buffer.
char *ff (char *s){
char *s1 = new char [strlen(s)];
strcpy(s1, s);
return s1;
}
int _tmain(int argc, _TCHAR* argv[])
{
char *s = new char [5];
strcpy(s, "hello");
char *s2 = ff(s);
delete []s; // This works normal
delete []s2; // But I get an error on that line
return 0;
}
Causes Undefined behavior(UB).
You are writing beyond the bounds of allocated memery. You allocated enough memory for
5characters but your string has6characters including the\0.Once your program has caused this UB, all bets are off and any behavior is possible.
You need:
In fact the ideal solution is to use
std::stringand notchar *. These are precisley the mistakes whichstd::stringavoids. And there is no real need of usingchar *instead ofstd::stringin your example.With
std::string:newanythingdeleteanything &std::string, that you do withchar *.