在函数中返回静态数组上的段错误

时间:2015-04-05 20:08:02

标签: c segmentation-fault gdb

我尝试使用gdb和“dissassemble”来调试它,但它没有显示行,只显示了它获取Segmentation fault的函数。

以下是代码:

应该检查玩家是否赢了(他是最后一个活着的),还是输了(他不再在地图上)

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

1 个答案:

答案 0 :(得分:0)

通过减慢进程(在while循环中进行休眠),seg故障停止。

我可以假设我在一个无限循环中要求过多的操作,并使一些溢出。

我不知道这是否是最好的答案,但这对我来说很好。请注意,如果您要求太多操作,无限循环可能会非常棘手。

以下是决赛:

   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);
相关问题