user5514267
user5514267

Reputation: 31

Segmentation Fault (Variant of Linked List)

I am getting a segmentation fault when i init_graph then do 5 add_vertex and then has_vertex.

P means it uses pointers

#define SIZE (graph.size)
#define PSIZE (graph->size)

#define NODE (graph.node)
#define PNODE (graph->node)

#define NAME (graph.node[i].name)
#define PNAME (((graph->node)+i)->name)

#define NUM_DEST (graph.node[i].num_dest)
#define PNUM_DEST (((graph->node)+i)->num_dest)

#define DESTCOST (graph.node[i].destcost[j])
#define PDESTCOST (((graph->node)+i)->destcost)

#define DEST_NAME (graph.node[i].destcost[j].dest_name)
#define PDEST_NAME (((((graph->node)+i)->destcost)+j)->dest_name)

#define COST (graph.node[i].destcost[j].cost)
#define PCOST (((((graph->node)+i)->destcost)+j)->cost)

checks to see if graph points to a non-NULL Graph and makes size counter 0

void init_graph(Graph *graph) {

  if (graph != NULL)

    PSIZE = 0;

}

adds new_vertex to list of node if it does not exist

int add_vertex(Graph *graph, const char new_vertex[]) {

i gets current size while size increases by 1

  int i = PSIZE++;

if new_vertex exists return 0

  if (has_vertex(*graph, new_vertex))

    return 0;

if size is not 1 reallocate room for another node

else allocate memory for the size of a node

then add the new_vertex and return 1

  if (PSIZE > 1)

    PNODE = realloc(PNODE, PSIZE * sizeof(node));

  else PNODE = malloc(sizeof(node));

  PNAME = malloc((strlen(new_vertex)+1) * sizeof(char));

  strncpy(PNAME, new_vertex, strlen(new_vertex)+1);

  return 1;

}

checks if vertex exists

int has_vertex(Graph graph, const char name[]) {

  int i;

checks to see if the name passed in is non-NULL

  if (name != NULL)

iterate over list of node

    for (i = 0; i < SIZE; i++)

check if: current node is name

if so: return 1

      if (strcmp(NAME, name) == 0)

        return 1;

  return 0;

}

Upvotes: 0

Views: 126

Answers (1)

milevyo
milevyo

Reputation: 2184

it is hard to understand your code, and definitely impossible to test it as it is incomplete code, but the thing that i can suspect is this:

//[1]
//i gets current size while size increases by 1
    int i = PSIZE++;

//[2]
//if new_vertex exists return 0
    if (has_vertex(*graph, new_vertex))
        return 0;

i think that the order is incorrect, you are incrementing PSIZE regardless of new_vertex exists or not

Upvotes: 1

Related Questions