I saw some code as below during a peer-code-review session:
char *s = new char[3];
*s++ = 'a';
*s++ = 'b';
*s++='\0';
delete []s; // this may or may not crash on some or any day !!
Firstly, I know that in Standard C++, pointing to one-past the array-size is O.K. though accessing it results in undefined behaviour. So I believe the last line *s++='\0'
is fine. But if I recall correctly, the C++ standard mandates that delete
should be supplied the same pointer that new
returned. This I believe means that the returned pointer must not be tampered-with. I guess it is because new
might keep some housekeeping info before the returned address that delete
might use. Moving the new
'd pointer might make this inaccessible.
Is it undefined behaviour or implementation-defined or unspecified? Can anyone confirm this please? Preferably by pointing to the correct place in the C++ Standard.
Thanks in advance,
EDIT-1: In the freely available draft version of the draft C++ Standard ( Draft_SC22-N-4411.pdf ) has the details in section 5.3.5. I got it from Bjarne's homepage.