作者jerrypotato (我是湯姆貓 不是傑利薯)
看板C_and_CPP
標題[問題] 要抓出存放Array Size的記憶體位置
時間Mon Oct 5 21:24:00 2009
現在課堂上正在複習C++語法
順便介紹變數宣告時 電腦是如何實際的指派記憶體位置給那些被宣告的變數
其中有一題是這樣的:(只列出關鍵部份)
class A
{
int data;
}
int main()
{
A *arr = new A[17];
//Some Commands......
return 0;
}
根據教授的說法,"17"這一個數字會實際存在於記憶體中,
而且其位置位於arr之前的幾個byte,
要我們定位出"17"這個數字,所佔據的記憶體位址。
我試過好幾個方法,可是最後都是失敗的,
最後還用到超級暴力法:
int *intptr = (int *) &arr //強制取出arr的記憶體位址
for (int k = 0; k < 50; k++ )
cout << *(intptr - k) << endl //把arr位址之前的記憶體全部掃瞄過一遍
結果還是不能掃到17這個數字 囧
實在沒辦法,只好PO上版來請教各位強者,
請問我要如何定位出"17"這個數字所佔據的記憶體位址呢?
謝謝<(_ _)>
--
BED ▎●▅ ▅
▎●▁▁
▎●▅▅▅
▎●▅▅
┌ ▎ ┐
▇▇▇ ▇ ▇▇▇▇ ▇▇▇▇ ●▅▅
▇▇▇▇ │ ▇▇▇▇ │
&
▎ ▎ ▎ ▎ ▎ ▎ ▎●▅▅
│ ▎ ▎│
▇▇▇▇ │ │
I magician super model basketball homeless prisoner
└ engineer
┘
player
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.243.205
1F:→ VictorTom:dynamic alloc回來的空間, 其大小不會直接放在該空間前 10/05 21:31
2F:→ VictorTom:後才對吧?? 這個資訊要也是放在heap管理相關的code裡, 10/05 21:32
3F:→ VictorTom:我想你應該先確認教授的問題, 我猜他想問的應該是code 10/05 21:33
4F:→ VictorTom:(翻好的)哪裡會讓你看到17. 如果是VC, 你可以disasm出來 10/05 21:33
5F:→ VictorTom:看, 組語碼找到new那行前後, 應該就會有地方算出來這個 10/05 21:34
6F:→ VictorTom:17怎麼換算與傳給OS讓它幫你配記憶體的. 10/05 21:34
7F:→ VictorTom:至於是local的, global的, static的, 又都是另一段故事 10/05 21:36
8F:→ VictorTom:了....XD 10/05 21:36
9F:推 VictorTom:話說, 他說的到底是arr這個pointer本身位址的前面還是 10/05 21:40
10F:→ VictorTom:arr指到的位址的前面啊?? 反正前者應該是錯的XD 10/05 21:40
11F:→ VictorTom:而你的code看起來就是用上一行說的錯的那種在找Orz 10/05 21:41
他的原文是 The array size "17" is recorded around "arr's" location in the heap
memory. (hint: some bytes before arr's address). please locate this piece of
memory and verify that the number in that memory is indeed "17".
因此我就把上面那段話想成要找出"17"的所在位置了 囧
※ 編輯: jerrypotato 來自: 140.112.243.205 (10/05 21:51)
12F:推 ADF:建議你trace delete[] 看compiler是怎麼實作的 10/05 22:06
13F:推 joefaq:我覺得那個"17"就跟一般的const變數放一起 10/05 22:11
14F:→ ilway25:資結!?xd 10/06 16:33