Consider the following:
char* msg = new char[20];
msg[4] = '\0';
delete[] msg;
delete[] msg
deallocate all the 20 chars allocated for msg
or just those up to the \0
? \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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With