Re: [問題] 關於指標轉換的問題....
※ 引述《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)
推
61.70.137.117 07/28, , 1F
61.70.137.117 07/28, 1F
→
61.70.137.117 07/28, , 2F
61.70.137.117 07/28, 2F
推
59.116.66.235 07/28, , 3F
59.116.66.235 07/28, 3F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章
-4
30