Consider the following:
char* msg = new char[20];
msg[4] = '\0';
delete[] msg;
- Did the
delete[] msgdeallocate all the 20 chars allocated formsgor just those up to the\0? - If it deallocated only up to the
\0, how can I force it to delete the entire block of memory?
The original code in your question had undefined behaviour, since you were using
deletewithnew[].I notice that you have fixed it by replacing the
deletewithdelete[]: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 withnew/new[]can be deleted, so your code is fine.