作者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