Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the below code really free memory in C/C++?

Tags:

c++

c

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?

like image 530
alphaplus Avatar asked Nov 27 '22 00:11

alphaplus


2 Answers

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.

like image 109
Gary Jackson Avatar answered Dec 12 '22 02:12

Gary Jackson


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.

like image 33
SergeyA Avatar answered Dec 12 '22 00:12

SergeyA