2011-01-11 109 views
0

我很震驚,爲什麼這段代碼給我一個分段錯誤?這爲什麼會導致分段錯誤?

#include <stdio.h> 

#define LIMIT 1500000 

typedef struct { 
    int p; 
    int a; 
    int b; 
} triplet; 

int main(int argc, char **argv) { 
    int i; 
    triplet triplets[LIMIT]; 

    for (i = 0; i < LIMIT; i++) { 
     triplets[i].p = 9; // remove this line and everything works fine 
    } 

    printf("%d\n", triplets[15].p); 

    return 0; 
} 

編輯:改變LIMIT 150我不再出現段故障後,它打印的隨機數代替。

EDIT2:現在我知道什麼網站名稱代表:)我使數組全球,現在一切正常。

+1

的數字是什麼碰巧在棧上做(因爲你只初始化前五個數組元素,但你打印16) 。 – Shog9 2011-01-11 23:53:58

+0

`它會打印隨機數字。'你究竟打印了什麼?顯示整個代碼。 – Mahesh 2011-01-12 00:02:01

+0

@Mahesh:請閱讀最後三行。 – orlp 2011-01-12 00:04:38

回答

10

堆棧溢出!以每條記錄12字節分配1500000條記錄(假設4字節爲int)需要超過17 MB的堆棧空間。讓你的triplets數組全局或動態分配它。

至於你的編輯 - 收縮陣列可能會停止堆棧溢出,但你的printf()呼叫仍將打印未初始化的數據 - triplets[15].p可能是你打印出來的時間什麼

4

當你

triplet triplets[LIMIT]; 

你分配的堆棧。這顯然對於你的系統來說太大了。

如果你

triplet* triplets=(triplet*)malloc(LIMIT*sizeof(triplet)); 

你將它分配在堆上,一切都應該罰款。一定要釋放內存當你用它

free(triplets);