2014-09-29 2 views
-1

C에서 질병 시뮬레이터를 프로그래밍하려고합니다. while (1) 루프를 약 20-25 회 반복 한 후 몇 가지 이유로 인해 segfaults가 발생합니다. 그것은 완전히 무작위입니다. 나는이 문제를 몇 시간 동안 고치려고 노력했기 때문에 어떤 도움이라도 대단히 감사 할 것입니다.Segfault on 질병 시뮬레이터

#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

+0

인덱스가 범위를 벗어나지 않았는지 확인하십시오. –

답변

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 (% 이하 &)이어야한다.