delete []提供了一个修改的newed指针。未定义行为? [英] delete[] supplied a modified new-ed pointer. Undefined Behaviour?

查看:149
本文介绍了delete []提供了一个修改的newed指针。未定义行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在同行代码审查期间,我看到了一些代码如下:

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 !!

首先,我知道在标准C ++中,指向一个数组大小。虽然访问它导致未定义的行为。所以我相信最后一行 * s ++ ='\0'很好。但是如果我记得正确,C ++标准要求 delete 应该提供与返回 new 相同的指针。

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.

我相信这意味着返回的指针不能被篡改。我想这是因为 new 可能在 delete 可能使用的返回地址之前保留一些内部信息。移动'd指针可能会导致无法访问。

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.

在C ++标准草案(Draft_SC22-N-4411.pdf)的免费草稿版本中,具有第5.3.5节的细节。

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.

推荐答案

从C ++标准,第5.3.5 / 2节:

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


delete的操作数的值必须是由前一个数组
new-expression产生的指针值
。如果没有,行为
未定义

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

这篇关于delete []提供了一个修改的newed指针。未定义行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆