作者khoguan (Khoguan Phuann)
看板C_and_CPP
标题Re: [问题] 关於指标转换的问题....
时间Thu Jul 28 15:37:11 2005
※ 引述《polor (...)》之铭言:
: int main(int argc, char* argv[])
: {
: int *a = new int;
: char *b , *c;
:
: b = (char*)a;
: c = b + 1;
:
: delete b;
:
: *c = 'a';
: *b = 'a';
:
: printf("Hello World!\n%c\n",*b);
: return 0;
: }
: b的记忆体已经被释放了....
: 程式到 *b = 'a'; 这一行应该会当掉才对...
: 但是却没事??请问是什麽原因吗??
: --
: → UNARYvvv:刚好没事罢了 61.70.137.117 07/28
就像 UNARY大大所说的,只是刚好没事而已。
原po的写法另外还有一个严重的问题:硬将 int* 的 a 转成 char* 然後
assign 给 b, 接着透过 b 去 delete 一个原本是 int 的物件。
依据 C++标准[注],这种 做法的下场是 undefined behavior, 凡是
undefined behavior 的行为都要绝对避免。
[注] 5.3.5/p3
In the first alternative (delete object), if the static type of
the operand is different from its dynamic type, the static type
shall be a base class of the operand's dynamic type and the static
type shall have a virtual destructor or the behavior is undefined.
In the second alternative (delete array) if the dynamic type of the
object to be deleted differs from its static type, the behavior is
undefined.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.130.208.168
※ 编辑: khoguan 来自: 220.130.208.168 (07/28 15:57)
1F:推 UNARYvvv:其实我就是在等k大拿规格来解释啊 XD 61.70.137.117 07/28
2F:→ UNARYvvv:先前觉得那种写法怪怪却没资料不敢多猜测.. 61.70.137.117 07/28
3F:推 StubbornLin:我一向是没资料就乱猜的 XD 59.116.66.235 07/28