Does [] remove the freeing of the entire memory block?

Consider the following:

char* msg = new char[20]; msg[4] = '\0'; delete[] msg; 
  • Did delete[] msg all 20 characters allocated for msg or only up to \0 ?
  • If it is freed only before \0 , how can I get it to delete the entire memory block?
+6
source share
3 answers

There was undefined behavior in the source code of your question since you used delete with new[] .

I noticed that you fixed it by replacing delete with delete[] :

 delete[] msg; 

This is correct and will free all memory allocated by new[] .

There is no concept of "deleting to \0 " or any other such "partial" deletion. Only complete blocks allocated with new / new[] can be deleted, so your code is fine.

+10
source

The delete[] operator deletes the entire memory block. You cannot free part of a memory block - you can only free an entire block.

This also applies to new/delete and malloc/free . The deallocating function can only free the entire memory block.

+5
source

You can use delete[] to free the array. This is the only way you can tell the program to look for information about the array and be able to free the entire array.

With plain delete compiler might think that you want to free only one pointer, and that is not the case. Additional information about the size of the array and what additional memory will not look for will not be freed.

The fact that you set char inside the array to \0 does not matter; when you release the array, only the known size of the array is considered. Otherwise, nothing like

 Class *array = new Class[50]; array[0] = NULL; delete[] array; 

just a memory leak.

+1
source

All Articles