2014-01-28 21 views
0

我有以下代碼,它適用於N = 10和C = 25罰款,但如果我使用N = 50和C = 25500炸彈與分段錯誤不知道爲什麼我得到一個分段錯誤初始化我的陣列

#include <stdio.h> 
#include <stdlib.h> 

// create table 
int *table; 
table = (int *) malloc(sizeof(int) * C+1 * N+1); 
if(table == NULL){ 
    printf("[ERROR] : Fail to allocate memory.\n"); 
} 

// initialize table 
for(i =0; i < N-1; i++){ 
    for(j = 0; j < C-1; j++){ 
    //table[i*(C+1)+j]=0; 
    *(table + (i*(C+1)+j))=1; 
    } 
} 
printf("table made\n"); 
+4

所以此工程沒有'主()'? – devnull

+2

確保malloc內部的數學運算正確無誤(可能是(C + 1)*(N + 1)) –

+0

您在哪裏得到了分段錯誤錯誤?把printf語句放在for循環中,並嘗試找出在哪個位置出現了分段錯誤。因爲如果malloc沒有爲大數分配任何內存,我們可以在'if(table == NULL)'條件中找到它。請試試這個 – arunb2w

回答

3

假設INT = 4,所以你分配

4*50 + 1*25500 + 1 = 25701 bytes 

在你的循環,你訪問(末尾):

i = 49 
j = 25499 

49*(25501)+25499 = 1275048(index)*4 = 5100192 (offset) 

所以,你需要的是:

table = malloc(sizeof(int) * (C+1) * (N+1)); 

您的循環不適用於較小的值,它只是沒有崩潰。寫外部分配的內存是未定義的行爲。

而作爲一個旁註,不相關的崩潰: Do I cast the result of malloc?

相關問題