Search code examples
c++memory-managementnew-operatorstandards-compliance

delete[] supplied a modified new-ed pointer. Undefined Behaviour?


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.

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.


Solution

  • From the C++ Standard, section 5.3.5/2:

    the value of the operand of delete shall be the pointer value which resulted from a previous array new-expression. If not, the behaviour is undefined