Re: [問題] 發生 EXCEPTION_DATATYPE_MISALIGNMENT
看板C_and_CPP (C/C++)作者littleshan (我要加入劍道社!)時間14年前 (2012/02/14 22:50)推噓5(5推 0噓 12→)留言17則, 2人參與討論串2/2 (看更多)
首先
char* buffer = new char[1024]; // a big buffer
int* pInt = reinterpret_cast<int*>(buffer);
double* pDouble = reinterpret_cast<double*>(buffer);
*pInt = 10;
*pDouble = 20.0;
這樣做是沒問題的,而且得到標準 (C++ 2003 3.7.3.1p2) 的保證:
The allocation function attempts to allocate the requested amount
of storage...The pointer returned shall be suitably aligned so that
it can be converted to a pointer of any complete object type and
then used to access the object or array in the storage allocated.
但是你不是這樣寫的啊!
你看看你怎麼寫:
int* pInt = reinterpret_cast<int*>(buffer);
*pInt = 10;
pInt++;
double* pDouble = reinterpret_cast<double*>(pInt);
原本的 buffer 保證符合 double alignment
但是你轉成 int* 之後改變了它的值
改變後當然就不一定符合 alignment 了
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.168.87.165
推
02/14 23:03, , 1F
02/14 23:03, 1F
→
02/14 23:04, , 2F
02/14 23:04, 2F
→
02/14 23:05, , 3F
02/14 23:05, 3F
→
02/14 23:18, , 4F
02/14 23:18, 4F
推
02/14 23:34, , 5F
02/14 23:34, 5F
→
02/14 23:34, , 6F
02/14 23:34, 6F
→
02/14 23:39, , 7F
02/14 23:39, 7F
推
02/14 23:45, , 8F
02/14 23:45, 8F
→
02/14 23:46, , 9F
02/14 23:46, 9F
→
02/14 23:46, , 10F
02/14 23:46, 10F
→
02/14 23:52, , 11F
02/14 23:52, 11F
推
02/15 00:06, , 12F
02/15 00:06, 12F
→
02/15 01:20, , 13F
02/15 01:20, 13F
推
02/15 09:00, , 14F
02/15 09:00, 14F
→
02/15 09:00, , 15F
02/15 09:00, 15F
→
02/15 09:01, , 16F
02/15 09:01, 16F
→
02/15 10:29, , 17F
02/15 10:29, 17F
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章