MRT89
MRT89

Reputation: 309

segmentation fault: 11 in C code

Why am I getting a segmentation fault with this code?

 /* 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 };

solver.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 }

output:

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

Segmentation fault: 11

Upvotes: 9

Views: 102940

Answers (3)

moonshadow
moonshadow

Reputation: 89055

board[9][9] will contain elements with indices in the range 0...8, not 1...9. When you assigned to board[9][whatever], you actually overwrote memory that didn't belong to you, and this happened to cause the program to explode when return 0 handed control back to the C runtime and it started walking its structures to perform shut down.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490018

some_type array[9]; defines array to be an array of 9 elements, with subscripts going from 0 to 8 inclusive. You can't use array[9].

Upvotes: 2

MByD
MByD

Reputation: 137272

Arrays are indexed from 0, so the loops should be for(i = 0; i<9; i++) and not for(i = 1; i<10; i++)

In your case, you probably override part of the stack, but in general, going out of boundaries results in undefined behavior.

Upvotes: 12

Related Questions