【问题标题】:segmentation fault: 11 in C code分段错误:C 代码中的 11
【发布时间】:2012-05-16 04:36:53
【问题描述】:

为什么这段代码会出现分段错误?

 /* solver.h header file */
 10 struct options{
 11     unsigned int one:1, two:1, three:1, four:1, five:1, six:1, seven:1, eight:1, nine:1;
 12 };
 13 
 14 
 15 /* structure to describe a cell */
 16 struct cell{
 17     short value;
 18     struct options open_options;
 19 };

求解器.c:

  5 #include <stdio.h>
  6 #include "solver.h"
  7 
  8 
  9 
 10 
 11 
 12 int main(){
 13         struct cell board [9][9];
 14         int i=0,j=0;
 15 
 16 
 17         for(i = 1; i<10; i++)
 18                 for(j = 1; j<10; j++)
 19                         (board[i][j]).value = j;
 20 
 21         for(i = 1; i<10; i++){
 22                 for(j = 1; j<10; j++)
 23                         printf(" %d",(board[i][j]).value);
 24                 printf("\n");
 25         }
 26         return 0;
 27 }

输出:

1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9

分段错误:11

【问题讨论】:

  • 您可以使用gdb开始自己调试代码
  • C 数组x 中的第一个元素是x[0]
  • 确实for(i=0; i &lt; 9; i++){} BTW:如果您打算实现数独求解器:位掩码会更容易,因为您可以一次扫描所有数字。
  • @wildplasser 是的,我现在看到了。我对C还是很陌生;我在想一个位域可以被类似地屏蔽。不过谢谢!
  • 每个单元格的位掩码不如每个行/列/框的位掩码有用。并且不要忘记有时你必须回溯(在你摘下低垂的果实之后)

标签: c segmentation-fault


【解决方案1】:

数组从 0 开始索引,因此循环应该是 for(i = 0; i&lt;9; i++) 而不是 for(i = 1; i&lt;10; i++)

在您的情况下,您可能会覆盖堆栈的一部分,但一般来说,超出边界会导致未定义的行为。

【讨论】:

    【解决方案2】:

    some_type array[9];array 定义为一个包含 9 个元素的数组,下标从 0 到 8(包括 0 到 8)。你不能使用array[9]

    【讨论】:

      【解决方案3】:

      board[9][9] 将包含索引在 0...8 范围内的元素,而不是 1...9。当您分配给board[9][whatever] 时,您实际上覆盖了不属于您的内存,当return 0 将控制权交回C 运行时并开始遍历其结构以执行关闭时,这恰好导致程序爆炸.

      【讨论】:

        猜你喜欢
        • 2019-01-22
        • 1970-01-01
        • 1970-01-01
        • 2021-09-17
        • 1970-01-01
        • 1970-01-01
        • 2014-04-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多