【问题标题】:Segmentation fault in DFS functionDFS 函数中的分段错误
【发布时间】:2019-11-20 14:27:11
【问题描述】:

第一次调用函数 dfs 时出现分段错误错误。

我尝试过使用动态和静态数组,但都以同样的错误告终。

void dfs(int **g,int *visitados,int prim,int nAlunos){
    int k;
    for(k=0;k<nAlunos;k++){
        if(!visitados[k] && g[prim][k] == true){
            dfs(g,visitados,k,nAlunos);
        }
    }
 }

主要:

    scanf("%d %d",&nAlunos,&    nLinhas);

   int **g = (int**)malloc(sizeof(int*)*nAlunos);  //matrix allocation
    for(a=0;a<nAlunos;a++)
        g[a] = (int *)malloc(nAlunos * sizeof(int));

    int *visitados = (int*)malloc(nAlunos * sizeof(int)); // visited array

    for(a=0;a<nAlunos;a++)      //set the full matrix as false
        for(b=0;b<nAlunos;b++)
            g[a][b] = false;

    for(a=0;a<nAlunos;a++)      //set the full array as false
        visitados[a] = false;

    for(a=0;a<nLinhas;a++){
        scanf("%d%d",&i,&j);
        g[i-1][j-1] = true; //input starts with 1
    }

    int grupos = 0;
    for(a=0;a<nLinhas;a++){
            if(visitados[a] == false){
                 dfs(g,visitados,a,nAlunos); //segfault when 1st calling this
                grupos++;
            }

程序收到信号SIGSEGV,分段错误。 0x000000000800095c in main()

【问题讨论】:

  • 您从未将任何访问设置为true
  • Segfault 与什么输入有关?
  • Stack Overflow 上的 Stack Overflow 错误!

标签: c segmentation-fault malloc breadth-first-search


【解决方案1】:

您从未将任何访问设置为true,因此到dfs 的递归永远不会终止。当然,直到堆栈溢出为止。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多