2014-09-29 89 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(%不&)。