Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does delete[] deallocate the entire block of memory?

Consider the following:

char* msg = new char[20]; 
msg[4] = '\0'; 
delete[] msg; 
  1. Did the delete[] msg deallocate all the 20 chars allocated for msg or just those up to the \0?
  2. If it deallocated only up to the \0, how can I force it to delete the entire block of memory?
like image 556
URL87 Avatar asked Dec 03 '12 17:12

URL87


1 Answers

The original code in your question had undefined behaviour, since you were using delete with new[].

I notice that you have fixed it by replacing the delete with delete[]:

delete[] msg;

This is correct, and will deallocate all memory that's been allocated by new[].

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

like image 185
NPE Avatar answered Sep 18 '22 05:09

NPE