2015-04-05 59 views
0

我試圖通過使用gdb和「dissassemble」來調試它,但它不顯示行,只是它獲取分段錯誤的函數。函數返回靜態數組上的Seg錯誤

這裏是代碼:

應該檢查,如果玩家獲勝(他是最後一個活着),或丟失(他是不是在地圖上了)

int * win_lose_verif(int number_of_player, int your_player); 

它是主循環,我需要它停止每當玩家贏得或失去

int network_fn(int number_of_player, int your_player); 

的完整代碼:

int * win_lose_verif(int number_of_player,int your_player) { 
    int i; 
    int j; 
    int is_our_player_alive=0; 
    int are_the_other_alive=0; 
    int* condition_win_lose; //[0]lose condition [1]win condition 

    condition_win_lose=(int*) malloc(sizeof(int)*2);   

    for (i=0; i<end_of_map_x-1; ++i) 
    { 
     for (j=0; j<end_of_map_y-1; ++j) 
     { 
      if (map[i][j] && (map[i][j]->species==P1||map[i][j]->species==P2||map[i][j]->species==P3||map[i][j]->species==P4)) 
      { 
       if(your_player==map[i][j]->species) //our player is here 
        is_our_player_alive++; 
       else 
        are_the_other_alive++; 
      } 
     } 
    } 

    if(is_our_player_alive==0) { 
     condition_win_lose[0]=1; 
    } 
    else { 
     condition_win_lose[0]=0; 
     condition_win_lose[1]=0; 
     if(are_the_other_alive==0) 
     { condition_win_lose[1]=1;  } 
    }  

    return condition_win_lose; 

} 



int network_fn(int number_of_player, int your_player) { 
    int tick=0; 
    int lose=0; 
    int win=0; 
    int* check_win_lose; // *(check_win_lose+0) for lose , +1 for win 

    do { 
     check_win_lose=win_lose_verif(number_of_player,your_player); 

     if (*(check_win_lose + 0)==1) { 
      return ENDGAME; 
     } 
     else if (*(check_win_lose + 1)==1) { 
      return ENDWIN; 
     } 

    } while (1); 

    return EXIT_SUCCESS; 
} 

這是我得到的gdb回溯後:

Program received signal SIGSEGV, Segmentation fault. 
0x0000000000403231 in win_lose_verif() 
(gdb) backtrace 
#0 0x0000000000403231 in win_lose_verif() 
#1 0x0000000000403cff in network_fn() 
#2 0x0000000000400db0 in main() 

我不明白爲什麼我得到段錯誤。

我沒有得到一個段錯誤的前20秒,但在那之後,我很可能得到它。爲什麼?

編輯:對於似乎不清楚的評論。我試圖用ggdb編譯,但我仍然沒有得到更多的信息。 如何讓gdb打印segfault的行?

我改變了靜態到的malloc

+0

編譯-g,在gdb設置斷點,檢查一些變量,並測試你的假設 – 2015-04-05 20:31:09

+0

的malloc的condition_win_lose陣列,而不是試圖返回一個靜態的範圍數組。 – 2015-04-05 20:48:07

+0

如果使用gcc作爲編譯器/鏈接器,則使用參數-ggdb。這會將最大量的調試信息放入可執行文件中。 -g只是簡單的調試信息。 -ggdb添加gdb可以使用的額外信息。 – user3629249 2015-04-05 20:56:23

回答

0

通過減慢的過程(在while循環睡眠),賽格故障停止。

我可以推測我在無限循環中要求太多的操作,並造成了一些溢出。

我不知道這是否是最好的答案,但對我來說工作正常。請注意,如果您要求操作太多,無限循環可能會非常棘手。

這裏是最後的:

do { 
     sleep(1); 
     check_win_lose=win_lose_verif(number_of_player,your_player); 

     if (*(check_win_lose + 0)==1) { 
      return ENDGAME; 
     } 
     else if (*(check_win_lose + 1)==1) { 
      return ENDWIN; 
     } 

    } while (1);