2012-05-13 171 views
0

我想知道這段代碼如何給內存訪問衝突?mem訪問衝突

{ 
    Vector3f *a = new Vector3f [10]; 
    Vector3f *b = a; 
    b[9] = Vector3f (2,3,4); 
    delete[] a; 
    a = new Vector3f [10]; 
    b[4] = Vector3f (1,2,3); 
    delete[] a; 
} 
+3

b仍然指向「老」a。 –

+1

注意:你使用的操作系統是什麼?你很幸運,它沒有默默地失敗.. –

回答

5

因爲b仍然指向同一個數組作爲a當你打電話delete[] a,然後嘗試使用該內存b[4]

Vector3f *a = new Vector3f [10]; // a initialised to a memory block x 
Vector3f *b = a;     // b initialised to point to x also 
b[9] = Vector3f (2,3,4);   // x[9] is assigned a new vector 
delete[] a;      // x is deallocated 
a = new Vector3f [10];   // a is assigned a new memory block y 
b[4] = Vector3f (1,2,3);   // x is used (b still points to x) 
           // x was deallocated and this causes segfault 
delete[] a;      // y is deallocated 
3

它這一行:

b[4] = Vector3f (1,2,3); 

b仍然指向舊的,釋放a

3

b指向第一個缺失a(即b沒有指向新分配a),所以當你試圖刪除它指向的內存後再次使用b,要調用未定義行爲,在這種情況下,它會給你一個內存訪問衝突。