John Henry Galino
John Henry Galino

Reputation: 347

Why does creating a linked list in my code create a segmentation fault?

I am trying to do an exercise on C. There are two arrays, count and list. count is an array of ints initially filled with 0, while list is an array of queues. My code is supposed to take pairs of numbers separated by a space eg. "1 2". For every pair of numbers, I must add 1 to the 2nd number-1 position in the count array, and then put a node containing the 2nd number in the head of the queue in the 1st number-1 position of the list array. My code is down below, and it results to a segmentation error after receiving the first pair of numbers. Removing lines 24-30 removes the error, but I don't understand what causes this error. Can anyone point out why it's doing a segmentation error?

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

typedef struct node Node;
struct node {
  int succ;
  Node *next;
};

void set_initial_array(int count[], int n, Node *list[]);
void handle_input(char string[], int count[], Node *list[]);

void set_initial_array(int count[], int n, Node *list[]) {
  for (int i = 0; i < n; i++) {
    count[i] = 0;
    list[i] = NULL;
  }
}

void handle_input(char string[], int count[], Node *list[]) {
  int j = atoi(&string[0]), k = atoi(&string[2]);
  count[k - 1]++;
  if (list[j - 1] != NULL) { // Removing line 24-30 removes error
    Node head = {k, list[j - 1]};
    list[j - 1] = &head;
  } else {
    Node head = {k, NULL};
    list[j - 1] = &head;
  }
}

int main() {
  char string[4];
  int count[15];
  Node *list[15];
  set_initial_array(count, n, list); //fill count with 0 and list with NULL
  while (fgets(string, 4, stdin) != NULL && strcmp(string, "0 0") != 0) {
    handle_input(string, count, list);
  }
}

Upvotes: 0

Views: 42

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50774

There is a problem here:

Node head = {k, list[j - 1]};
list[j - 1] = &head;

head is a local variable, which will go of scope (or in simple terms: it will be destroyed) as soon as the handle_input function returns.

In this line list[j - 1] = &head; you store the address of that local variable in the list array which points actually to an array provided in main.

You need to handle this differently by allocating memory:

Node *head = malloc(sizeof(*head));
head->succ = k;
head->next = list[j - 1]
list[j - 1] = head;

There may be other problems though, I didn't check.

Don't forget to free the allocated memory at some point in main.

Upvotes: 1

Related Questions