Here is the code:
int main()
{
char str[] = {'a','b','c',' ','d','e',' ',' ','f',' ',' ',' ','g','h','i',' ',' ',' ',' ','j','k'};
cout << "Len = " << strlen(str) << endl;
char* cstr = new char[strlen(str)];
strcpy(cstr, str);
cstr[5] = '\0';
cout << "Len= " << strlen(cstr) << endl;
return 0;
}
//---------------
Result console:
Len = 21
Len= 5
As you see the Len of cstr changed. It mean that remain memory area of cstr is free. Is it right?
No. All strlen() does is look for the first null character ('\0') in the string. It doesn't free memory. It doesn't even care if the memory it examines is properly allocated. It will happily walk past the end of allocated memory in search of a null character if none is found starting from the pointer you give it.
The code is broken from the starts. str
is not a nul-terminated string, and as such can't be used with functions expecting those strings, such as strlen
or strcpy
.
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