Home > Blockchain >  Segmentation fault (core dumped) error in C when Implementing list ADT
Segmentation fault (core dumped) error in C when Implementing list ADT

Time:11-28

I'm trying to implement a list ADT in C but I keep getting the error "Segmentation fault (core dumped)". I know it is caused by accessing memory that cannot be used, but I have no idea how to fix it (I am very new to data structures so sorry if there's an obvious error)

Here's the list.h file:

typedef struct node NodeType;

struct node {
  int num;
  NodeType *next;
};

typedef struct {
  int length;
  NodeType *head;
} List;

void init(int maxSize, List *L);
void add(List *L, int num);
void print(List L); 

and this is the list.c file:

#include <stdio.h>
#include <stdlib.h>
#include "list.h"
void init(int maxSize, List *L) {
   (*L).length = maxSize;
   (*L).head=NULL;
}

void add(List *L, int num) {
  NodeType *new;
  new=(NodeType *) malloc(sizeof(NodeType));
  (*new).num = num;
  (*new).next = (*L).head;
  (*L).head = new;
  (*L).length  ;
}
void print(List L) {
 int i; 
 NodeType *p;

 printf("List is: ");
 for (i=0, p=L.head; i<L.length; i  , p=(*p).next) {
   printf(" %d ", (*p).num);
 }
 putchar('\n');
}

and this is the main file:

#include <stdio.h>
#include <stdlib.h>
#include "list.h"


int main(void){
  List L;
  init(10, &L);
  add(&L, 20); add(&L, 41); add(&L, 63);
  print(L);
  return 0;
}

what should I do? which part is exactly wrong?

CodePudding user response:

Linked lists do not traditionally track their length. Length rather is calculated by iterating until we hit a null pointer.

In your code, your init function sets the length of the list to 10. Then in print, you use this value to iterate 10 times, despite the fact that there are only 3 elements in your list. This is causing your segmentation fault.

You can add a check to print to avoid this:

 for (i=0, p=L.head; i<L.length && p != NULL; i  , p=(*p).next) {
   printf(" %d ", (*p).num);
 }

But I think you really need to rethink why you're initializing length to 10 at all, and why you're tracking the length of a list this way at all.

  • Related