A memory leak occurs when a memory was allocated by the programmer using the operator new
and was not deleted using the operator delete
or delete []
.
In this declaration
char arr[] = "some string";
It is the compiler (or the system) allocated memory for the character array arr that has either the automatic storage duration or the static storage duration. So the compiler (or the system) are responsible to free the allocated memory. The address of the allocated memory is known to the compiler (or the system).
Using this statement
arr[5] = '\0';
you did not reallocate the array. You just changed its content more precisely only one its byte.
How compiler will know that it must free memory after first '\0'?
(when will delete variable arr)
Because the compiler (or system) knows how the object of the array type was declared.
For the object there was allocated 12 bytes.
char arr[] = "some string";
Is it possible to change lenght of this arr variable and notify
compiler how much it should free when delete variable?
I think you mean the size of the object. No, you can not change the size of the object because it was not you who allocated the memory for the object.
You could reallocate the object if you used the operator new
to allocate it as for example
char *arr = new char[12];
std::strcpy( arr, "some string" );
//...
char *tmp = new char[20];
strcpy( tmp, "another " );
strcat( tmp, arr );
delete [] arr;
arr = tmp;