2013-03-06 108 views
0

我應該爲我的char **分配足夠的內存。我使用gdb並找到了分段錯誤的一點。我一直被困在這個部分大約一個小時,似乎無法弄清楚爲什麼我會違規。無法弄清楚我是如何得到seg錯誤

輸出程序的:

尺寸:10,20

開始:1,1

端:10,20

分段故障(核心轉儲)

10 = m1.xsize 
20 = m1.ysize 
1 = m1.xstart 
1 = m1.ystart 
10 = m1.xend 
20 = m1.yend 

我的代碼片段:

typedef struct mazeStruct 
{ 
    char** arr; 
    int xsize, ysize; 
    int xstart, ystart; 
    int xend, yend; 
} maze; 



/* read in the size, starting and ending positions in the maze */ 
    fscanf (src, "%d %d", &m1.xsize, &m1.ysize); 
    fscanf (src, "%d %d", &m1.xstart, &m1.ystart); 
    fscanf (src, "%d %d", &m1.xend, &m1.yend); 

    /* print them out to verify the input */ 
    printf ("size: %d, %d\n", m1.xsize, m1.ysize); 
    printf ("start: %d, %d\n", m1.xstart, m1.ystart); 
    printf ("end: %d, %d\n\n", m1.xend, m1.yend); 

    //allocating memory for 2d char array 
    m1.arr = (char**)malloc(m1.xsize+2 * sizeof(char*)); 

    for(i = 0; i < m1.xsize+2; i++) 
     m1.arr[i] = (char*)malloc(m1.ysize+2); 

    /* initialize the maze to empty */ 
    for (i = 0; i < m1.xsize+2; i++) <---- when i = 6 it seg faults 
     for (j = 0; j < m1.ysize+2; j++) 
      m1.arr[i][j] = '.'; 

我沒有分配足夠的內存,或者我做錯了什麼?

回答

5

你的表達:

m1.xsize + 2 * sizeof(char*) 

等同於:

(m1.xsize) + (2 * sizeof(char*)) 

由於運營商的優先級,這是你想要什麼。您需要改用:

(m1.xsize + 2) * sizeof(char*) 

舉例來說,假設你有m1.xsize設置爲20和指針大小爲四個字節。因此,您需要22個指針的空間,即88個字節。表達式m1.xsize + 2 * sizeof(char*)給你20加上一個指針大小的兩倍,總共28個字節,遠遠不夠你想做的事情。


順便說一句,你也應該停止鑄造malloc()的返回值,因爲它可以隱藏某些細微的錯誤。 C完全能夠隱含地將從malloc()返回的void*轉換爲任何其他指針類型。

+0

非常感謝。這是我犯的一個非常愚蠢的簡單錯誤。非常感激。 – juice 2013-03-06 08:33:57