【问题标题】:Can't figure out how I am getting a seg fault无法弄清楚我是如何遇到段错误的
【发布时间】:2013-03-06 06:34:25
【问题描述】:

我应该为我的 char** 分配足够的内存。我使用gdb并找到了分段错误的点。我已经在这部分卡了大约一个小时,似乎无法弄清楚我为什么会出现段错误。

程序输出:

尺寸:10、20

开始:1、1

结束:10、20

分段错误(核心转储)

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

我的代码的sn-p:

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] = '.';

是我没有分配足够的内存还是我做错了什么?

【问题讨论】:

    标签: c struct segmentation-fault


    【解决方案1】:

    你的表情:

    m1.xsize + 2 * sizeof(char*)
    

    相当于:

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

    由于运算符的优先级,这不是你想要的。您需要改为使用:

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

    例如,假设您将m1.xsize 设置为 20,并且您的指针大小为 4 个字节。因此,您需要 22 个指针的空间,即 88 个字节。表达式 m1.xsize + 2 * sizeof(char*) 给你 20 加上两倍的指针大小,总共 28 个字节,远远不够你想做的事情。


    顺便说一句,您还应该停止转换 malloc() 的返回值,因为它可以隐藏某些细微的错误。 C 完全有能力将从malloc() 返回的void* 隐式转换为任何其他指针类型。

    【讨论】:

    • 非常感谢。这是我犯的一个非常愚蠢的简单错误。非常感谢。
    猜你喜欢
    • 2022-01-23
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多