Segmentation Fault in array of Structs C

1

I'm trying to make an array of dynamic structs in C, however I'm not understanding why it's returning me segmentation fault.

The code is basically this:

I'm just creating a vector of 10 arrays and then trying to initialize each struct individually, can anyone 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;

}
    
asked by anonymous 09.10.2014 / 14:49

2 answers

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

Reading this code very carefully: Calculate the size of a pointer to a struct and allocate a number of 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));

Of course, the parentheses in numVertices and type conversion in the end are redundant. You can only write:

grafo = malloc(numVertices * sizeof(struct Node));
    
09.10.2014 / 15:04
0

The size of each element is wrong.

//grafo =  (Node*) malloc((numVertices) * sizeof(struct Node*));
grafo = malloc(numVertices * sizeof *grafo);
    
09.10.2014 / 15:04