2

I can't seem to figure out why I am getting this error. I run valgrind and it says that the newNode = (NodeType *)malloc(sizeof(NodeType)); is creating the error, but I can't figure out why... Basically what I'm trying to do is initialize a linked list of size n passed in and setting the head to the first node.

typedef struct {
  int number;
  AnotherNodeType *anotherLinkedList;
} Type;

typedef struct Node{
  Type *data;
  struct Node *next;
} NodeType;


int main(){
  NodeType *nodePointer = NULL;
  initLinkedList(&nodePointer, 10);
  return 0;
}

void initLinkedList(NodeType **nodePointer, int n){
  int i;
  NodeType *prevNode, *newNode;
  prevNode = NULL;
  for (i = 0; i < n; i++){
    newNode = (NodeType *)malloc(sizeof(NodeType));
    newNode->data = (Type *)malloc(sizeof(Type));
    newNode->data->number = i;
    newNode->data->anotherLinkedList = NULL;
    if (prevNode == NULL){
      *nodePointer = newNode;
    }
    else{
      prevNode->next = newNode;
    }
    prevNode = newNode;
  }
}
Andrew B
  • 71
  • 1
  • 6

2 Answers2

2

You are not initializing newNode->next in initLinkedList.

aib
  • 45,516
  • 10
  • 73
  • 79
2

As said @aib, you are not initializing the 'next' element of the last item of your list.

You should initialize it to null right after the malloc.

Problem is : When you will loop through your list, when you reach the last item, the "next" value of it will be uninitialized, and you will probably end segfaulting, you have to init this to null to know you've reached the end of the list.

Intrepidd
  • 19,772
  • 6
  • 55
  • 63