0

I was learning how to create an array of linked lists for the pset5 problem. But i keep getting a segmentation fault when I go through a character linked lists a second time. Some kind of address keep entering into the previous node link address even though it is supposed to be NULL. Any help is appreciated.

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

typedef struct Node{
char word[50];
struct Node* link;
}
Node;
Node* dictHash[26];
void Print(Node* head){
Node* temp1 = head;
  while(temp1 != NULL){
    printf("%s\n", temp1->word);
    temp1 = temp1 -> link;
  }
}

int main(void){

  char inputWord[50];
  int room;
  Node* address;

  for(int i = 0; i < 5; i++){
    printf("Word %i is : \n", i+1 );
    Node* temp =  malloc(sizeof(Node*));
    scanf("%s",inputWord);

    room = inputWord[0] - 97;
    strcpy(temp->word,inputWord);
    temp->link = dictHash[room];
    dictHash[room] = temp;
    Print(dictHash[room]);
    address = temp->link;
  }
}

1 Answer 1

1

It's always the simple ones that hide in plain sight. ;-) Look very carefully at this:

Node* temp =  malloc(sizeof(Node*));

The code allocates memory space that is sizeof what? A node or a pointer?

As a side note, why does the code increment i inside the for loop and as the index of the for loop?

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .