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

放肆的年华 提交于 2019-12-01 17:51:45

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

Yes, you must delete[] the original pointer you were given by new; in this case, that would be a pointer to the head of the array, rather than the tail. The code here is deleting some other unspecified random object.

Yeah, recall how this is often implemented: new really calls malloc, which gives back a pointer to (void*)(&(((int*)p)[1])), where p is the actual start of the memory allocated, and the first int is the size of the actual memory we got back.

The pointer we get back is one sizeof(int) (or whatever alignment requires) further along in the actual memory allocated. We lay down our object there, leaving the actual size undisturbed.

Then when that pointer passed to delete, which passes it to free, free looks one int before the passed pointer, to find the size that's being given back.

Passing back something other than what we got is going to mean that free thinks an arbitrary amount of actual memory is being passed back, and it'll screw up the free list accordingly.

Again, this is how it's often implemented, not how new, delete, malloc, or free are required to be implemented.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!