0
votes

I'm getting a segmentation fault error when first calling the function dfs.

I've tried using dynamic and static arrays for it, but both ended up with the same error.

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);
        }
    }
 }

main:

    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++;
            }

Program received signal SIGSEGV, Segmentation fault. 0x000000000800095c in main ()

1
You never set any visitado to true. - user58697
Segfault with what input? - David Schwartz
Stack Overflow error on Stack Overflow! - George Ogden

1 Answers

0
votes

You never set any visited to true, so the recursion into dfs never terminates. Until the stack overflow, of course.