I need to create a program which takes songs and outputs them as a playlist. It's my first time working with malloc and linked lists and I am getting a segmentation fault and I don't know where it is from. I don't think I have overallocated any memory and don't know how to debug or use gdb to solve this issue.
song.h header file
#ifndef SONG_H
#define SONG_H
struct song {
char name[50];
char artist[50];
int duration;
char genre[50];
struct song* next_song;
int ID_in_playlist;
};
struct song *getValue (int id);
void Song_New (void);
void Song_Print (void);
void print1song (struct song *ptr);
void CleanUp(struct song *list);
void clean(void);
#endif
song.c file
#include <stdio.h>
#include <stdlib.h>
#include "song.h"
struct song * firstSong = NULL;
struct song * addedSong = NULL;
struct song *getValue (int id){
struct song * ptr = NULL;
ptr = malloc(sizeof(struct song));
if (ptr != NULL){
ptr->next_song = NULL;
ptr->ID_in_playlist = id;
printf("Type in your song name: ");
scanf("%s", ptr->name);
printf("Type in your artist name: ");
scanf("%s", ptr->artist);
printf("Type in your song duration (in seconds): ");
scanf("%d", &ptr->duration);
printf("Type in your song genre: ");
scanf("%s", ptr->genre);
}
else{
printf("Allocation Failure!\n");
}
return ptr;
}
void print1song(struct song *ptr){
if (ptr == NULL)
{
printf("The value is NULL\n");
}
else{
printf("Name: %s", ptr -> name);
printf(" Artist: %s", ptr -> artist);
printf(" Duration: %i", ptr -> duration);
printf(" Genre: %s", ptr -> genre);
printf("ID: %d\n", ptr -> ID_in_playlist);
}
return;
}
void Song_New(){
int counter = 1;
if (firstSong == NULL){
firstSong = getValue(1);
if (firstSong != NULL){
addedSong = firstSong;
}
}
else{
addedSong->next_song = getValue(counter+1);
if(addedSong->next_song != NULL){
addedSong = addedSong->next_song;
}
}
printf("Song added successfully!\n");
counter = counter + 1;
}
void Song_Print (){
struct song *t;
t = firstSong;
if(t == NULL){
printf("List is empty\n");
}
else{
while(t){
print1song(t);
t = t->next_song;
}
}
}
void CleanUp(struct song *list){
struct song *next;
while(list)
{
next = list->next_song;
free(list);
list = next;
}
}
void clean(void){
CleanUp(firstSong);
firstSong = NULL;
addedSong = NULL;
return;
}
main.c file
#include <stdio.h>
#include <stdlib.h>
#include "song.h"
int main (void){
int ans;
while(1){
printf("Press 1 to add a new song\n");
printf("Press 2 to print your songs\n");
printf("Press 3 to quit\n");
printf("Input: ");
scanf("%d", ans);
if (ans == 1){
Song_New();
}
if (ans == 2){
Song_Print();
}
if (ans == 3){
printf("Exiting program...");
break;
}
}
clean();
return 0;
}