Working on a pokedex project using linked lists, after creating a node and attempting to print I am getting this error I am pretty new to C so would not be surprised if this is a stupid mistake.
signal: segmentation fault (core dumped)
This is my code
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Pokemon {
char pokemonName[50];
char pokemonType[20];
char pokemonAbility[50];
struct Pokemon *next;
} Pokemon;
Pokemon* NewPokemonNode(char pokemonName[50],char pokemonType[20], char pokemonAbility[50]) {
Pokemon *new_node = NULL;
new_node = malloc(sizeof(Pokemon));
if (new_node != NULL){
strcpy(new_node -> pokemonName, pokemonName);
strcpy(new_node -> pokemonType, pokemonType);
strcpy(new_node -> pokemonAbility, pokemonAbility);
new_node->next = NULL;
}
return new_node;
}
int main(void){
Pokemon *head = NULL;
NewPokemonNode("Bulbasaur", "Grass", "Overgrow");
Pokemon *tempPointer = head;
while (tempPointer->next != NULL)
{
printf("Working");
tempPointer = tempPointer->next;
}
}
CodePudding user response:
You are getting segmentation fault because your code is dereferencing a NULL pointer.
Here, pointer head assigned NULL:
Pokemon *head = NULL;
and then tempPointer is assigned head:
Pokemon *tempPointer = head;
and then dereferencing tempPointer here:
while (tempPointer->next != NULL)
May you want to assign the return value of NewPokemonNode() function to head pointer. But note that, NewPokemonNode() function may also return NULL, in case, when malloc() fails. So you should take care of that as well. Change the while loop condition to tempPointer != NULL.
Pokemon *head = NULL;
head = NewPokemonNode("Bulbasaur", "Grass", "Overgrow");
Pokemon *tempPointer = head;
while (tempPointer != NULL)
{
printf("Working");
tempPointer = tempPointer->next;
}
