Is the code below really free memory in 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 can see, Len from cstr has changed. This means that the cstr memory area is free. Correctly?

+4
source share
6 answers

No. All strlen () searches for the first null character ('\ 0') in the string. This does not free memory. It doesn’t even matter if the memory that he is looking at is allocated correctly. He will happily walk past the end of the allocated memory in search of a null character, if none are found, starting with the pointer that you give him.

+15
source

. str nul-terminated , , strlen strcpy.

+7

, Len cstr . , cstr . ?

. . , \0 . - strlen , 5 ( char, \0), , , . , delete [] cstr.

+5

. new . - delete .

strlen - , NUL-, C-.

NUL - .

+4

, Len cstr . , cstr . ?

. strlen , , . 0 strlen(str) - 1, cstr strlen(str).

, , , , . , cstr, - delete.

+4

, , str .


strlen(cstr) , NUL \0.

char 22 char. a char NUL \0 , strlen , 5 char . 17 char, char char.

The memory for the array char strwill get get unallocated after exiting the function main()(since this is a local array).

+2
source

Source: https://habr.com/ru/post/1622232/


All Articles