2014-09-29 87 views
-1

我正尝试在C中编写疾病模拟器。出于某种原因,在while(1)循环的大约20-25次迭代之后,它会发生段错误。它是完全随机的。我一直试图解决这个问题几个小时,所以任何帮助将不胜感激。疾病模拟器上的Segfault

#include <stdio.h> 
#include <stdbool.h> 
#include <stdlib.h> 

typedef struct space { 
int type; 
int x, y; 
} space_t; 

space_t space[40][40]; 



int main(){ 

bool infected = false; 
int i = 0; 
int x = 0; 
int y = 0; 

srand(time(NULL)); 

while(i < 1600){ 
    space[x][y].x = x; 
    space[x][y].y = y; 
    if(rand() % 9 == 0 && !infected){ 
     space[x][y].type = 1; 
     infected = true; 
    } 
    if(rand() % 20 == 8){ 
     space[x][y].type = 2; 
    } 

    x++; 
    i++; 
    if(x == 40){ 
     x = 0; 
     y++; 
    } 
} 

system("clear"); 

int count; 
int inf = 0; 

while(1){ 

x = 0; 
y = 0; 
i = 0; 

    while(i < 1600){ 
     if(space[x][y].type == 1){ 
      inf++; 
     } 
     if(space[x][y].type == 1 && rand() % 9 > 4){ 
      if(rand() % 9 > 4){ 
       space[x+(rand() % 3)][y].type = 1; 
      } else { 
       space[x+(-(rand() % 3))][y].type = 1; 
      } 
     } else if(space[x][y].type == 1 && rand() & 9 > 4){ 
      if(rand() % 9 > 4){ 
       space[x][y+(rand() % 3)].type = 1; 
      } else { 
       space[x][y+(-(rand() % 3))].type = 1; 
      } 
     } 
     if(space[x][y].type == 1){ 
      printf("[I]"); 
     } else if(space[x][y].type == 2){ 
      printf("[D]"); 
     } else printf("[ ]"); 
     x++; 
     i++; 
     if(x == 40){ 
      printf("\n"); 
      x = 0; 
      y++; 
     } 
    } 
    count++; 
    printf("%d\n", count); 
    printf("%d\n", inf); 
sleep(1); 
system("clear"); 
} 

return 0; 
} 
+0

'&& rand()&9> 4' - > &&'rand()%9> 4'?怀疑这解释了塞尔错误,但看起来错了。 – chux 2014-09-29 17:08:35

+0

检查您的索引是否超出范围。 – 2014-10-01 17:21:16

回答

1

代码为索引生成随机偏移量,但不保证适当的范围。

if(space[x][y].type == 1 && rand() % 9 > 4){ 
    if(rand() % 9 > 4){ 
     // Nothing forces `x+(rand() % 3)` in legal index range. 
     space[x+(rand() % 3)][y].type = 1; 
    } else { 
     space[x+(-(rand() % 3))][y].type = 1; 
    } 
} 

相反

if(space[x][y].type == 1 && rand() % 9 > 4) { 
    int r = rand(); 
    if(r % 9 > 4) { 
     int offset = x + r%3; 
     if (offset < 40) space[offset][y].type = 1; 
    } else { 
     int offset = x - r%3; 
     if (offset >= 0) space[offset][y].type = 1; 
    } 
} 
... // similar change for next block 

注:后来的代码,当然rand() & 9rand() % 9(%不&)。