2013-03-06 103 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