Re: [問題] 發生 EXCEPTION_DATATYPE_MISALIGNMENT

看板C_and_CPP (C/C++)作者 (我要加入劍道社!)時間14年前 (2012/02/14 22:50), 編輯推噓5(5012)
留言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
L大 針對你說的"改變後當然就不一定符合 alignment"
02/14 23:03, 1F

02/14 23:04, , 2F
這相關的觀念該去看哪邊學習呢, 對於甚麼padding , alignment
02/14 23:04, 2F

02/14 23:05, , 3F
沒有對於這方面有相關認知@@ 比較無法體會改值會出錯的關鍵
02/14 23:05, 3F


02/14 23:34, , 5F
我看完了@@不過還是無法體認 說 轉成int改值後會不一定符合
02/14 23:34, 5F

02/14 23:34, , 6F
alignment是為什麼耶~我不是改值嗎 我沒有動記憶體位址阿~
02/14 23:34, 6F

02/14 23:39, , 7F
pLongLongPtr++; 這不就是改位址嗎
02/14 23:39, 7F

02/14 23:45, , 8F
喔喔~那若照原來那篇網頁的寫法 可以嗎? 我照他用memcpy
02/14 23:45, 8F

02/14 23:46, , 9F
就沒發出exception, 但是這並沒有避免misalignment吧?
02/14 23:46, 9F

02/14 23:46, , 10F
我跳的記憶體offset是一樣的!?
02/14 23:46, 10F

02/14 23:52, , 11F
為什麼你不用struct?
02/14 23:52, 11F

02/15 00:06, , 12F
因為.....其實我不太理解L大你說的struct + union.....
02/15 00:06, 12F

02/15 01:20, , 13F
union是我誤解了你的意思 你要的用struct就夠了
02/15 01:20, 13F

02/15 09:00, , 14F
所以我需要另外定義一個struct 然後把要寫得資料
02/15 09:00, 14F

02/15 09:00, , 15F
先做一堆的assign 在把整個struct寫下去嗎?
02/15 09:00, 15F

02/15 09:01, , 16F
因為我要寫的資料是某class的某幾個data member~
02/15 09:01, 16F

02/15 10:29, , 17F
對,不過如果是寫到檔案或網路上,要注意endian
02/15 10:29, 17F
文章代碼(AID): #1FEdJ1HL (C_and_CPP)
文章代碼(AID): #1FEdJ1HL (C_and_CPP)