Delete [] provided the modified new pointer. Undefined Behavior?

During the code review session, I saw the code as shown below:

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 a single value, the size of the array is OK, although access to it leads to undefined behavior. So I think the last line *s++='\0'is fine. But if I remember correctly, then the C ++ standard states that deletethe same pointer should be provided as new.

This, I believe, means that the returned pointer should not be tampered with. I assume this is because it newmay contain some home information before the return address that can be used delete. Moving the pointer new'd may make this inaccessible.

Is this undefined behavior or a specific or indefinite implementation? Can someone please confirm this? Preferably, pointing to the right place in the C ++ standard.

The freely available draft draft of the C ++ standard (Draft_SC22-N-4411.pdf) contains detailed information in Section 5.3.5. I got it from the Bjarne homepage.

+5
source share
3 answers

From the C ++ standard, section 5.3.5 / 2:

the value of the delete operand must be the value of the pointer that arose from the previous array of the new expression. If not, the behavior is undefined

+17
source

, [] , ; , . .

+4

, , : new malloc, (void*)(&(((int*)p)[1])), p - , int - , .

, , - sizeof (int) ( ) . , .

Then, when this pointer is passed for deletion, which transfers it to free, one int in front of the passed pointer looks for free to find the size that is being returned.

Rejecting something other than what we received will mean that the free one thinks that an arbitrary amount of actual memory is being transferred back, and this will spoil the free list accordingly.

Again, this is how it is often implemented, and not like new, delete, malloc or free.

+3
source

All Articles