Segmentation Fault in Structs C array

Asked

Viewed 115 times

1

I’m trying to make an array of dynamic structs in C, but I don’t understand why it’s returning to me.

The code is basically this:

I’m just creating a vector of 10 arrays and then trying to initialize each struct individually, someone can help me?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define MAX_NODES 10000
#define INF 999999999

typedef struct Node{  
        int value;  
        int listaAdj[MAX_NODES];  
        int pesoArestas[MAX_NODES];  
        int visited;  
}Node;

//variaveis globais
Node *grafo;
int numVertices = 10;


int main(){

    int i,j;
    grafo =  (Node*) malloc((numVertices) * sizeof(struct Node*)); 


    for ( i = 0; i < numVertices; i++ ){
            if ( i == 0 ){
                    grafo[i].value = 0;            
            }else{
                    grafo[i].value = INF;          
            }

            for ( j = 0; j < MAX_NODES; j++ ){
                    grafo[i].listaAdj[j] = -1;
                    grafo[i].pesoArestas[j] = -1;          
            }
    grafo[i].visited = 0;
    }


    for ( i = 0; i < numVertices; i++ ){
            printf(" %d \n", grafo[i].value);
    }

    free(grafo);

    return 0;

}
  • Sorry guys, I can’t code my question, how do I do that?

  • Pasting it and using the appropriate marker in the editor. This is what appears { }

  • And now I’m on show, they can spot the problem?

  • Ps: forgot to put, MAX_NODES is set to 10,000

  • @avoid because you took a relevant part of the code? This way it became difficult to solve something.

  • my entire code is there, only missing imports of stdlib and stdio

  • It wasn’t, you had it off and I put it back.

  • 2

    @avoid, Whenever it is a question of the type "why my code doesn’t work?", remember to include a code complete and compilable on the question. Without this others have neither how to test.

  • See more on http://answall.com/help/mcve

Show 4 more comments

2 answers

2


grafo = (Node*)malloc((numVertices) * sizeof(struct Node*)); 

Reading this code very carefully: Calculate the size of a pointer to struct and allocate a certain number of these pointers. I believe you want to allocate structs and not pointers to structs. Remove the last asterisk from the line, like this:

grafo = (Node*)malloc((numVertices) * sizeof(struct Node));

And of course, the parentheses in numVertices and the type conversion at the end is redundant. You can write only:

grafo = malloc(numVertices * sizeof(struct Node));
  • It worked man, thank you very much!!

0

The size of each element is wrong.

//grafo =  (Node*) malloc((numVertices) * sizeof(struct Node*));
grafo = malloc(numVertices * sizeof *grafo);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.