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; }
char* means a pointer to a character. In C strings are an array of characters terminated by the null character.
List of points to be noted: 1) You need to allocate room for n characters, where n is the number of characters in the string, plus the room for the trailing null byte. 2) You then changed the thread to point to a different string. So you have to use delete[] function for the variable you are created using new[] .
You can create an array with zero bounds with the new operator. For example: char * c = new char[0]; In this case, a pointer to a unique object is returned. An object created with operator new() or operator new[]() exists until the operator delete() or operator delete[]() is called to deallocate the object's memory.
To declare a char variable in C++, we use the char keyword. This should be followed by the name of the variable. The variable can be initialized at the time of the declaration. The value of the variable should be enclosed within single quotes.
char *s = new char [5]; strcpy(s, "hello");
Causes Undefined behavior(UB).
You are writing beyond the bounds of allocated memery. You allocated enough memory for 5
characters but your string has 6
characters including the \0
.
Once your program has caused this UB, all bets are off and any behavior is possible.
You need:
char *s = new char [strlen("hello") + 1];
In fact the ideal solution is to use std::string
and not char *
. These are precisley the mistakes which std::string
avoids. And there is no real need of using char *
instead of std::string
in your example.
With std::string
:
new
anythingdelete
anything &std::string
, that you do with char *
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With