c - 模块化编程的 C 分段错误
问题描述
我需要创建一个程序来获取歌曲并将它们作为播放列表输出。这是我第一次使用 malloc 和链表,我遇到了分段错误,我不知道它来自哪里。我认为我没有过度分配任何内存,也不知道如何调试或使用 gdb 来解决这个问题。
song.h 头文件
#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
歌曲.c 文件
#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 文件
#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;
}
解决方案
推荐阅读
- r - 如何在 R 中记录(x + 1)数据框或矩阵
- django - 给定模型字段中所有选项的 Django 表单集,其中预填充了选项字段的值
- node.js - Node.js 连接到 Neo4j 运行相同的代码给出不同的结果
- node.js - 如何在同一台服务器上运行 node 和 apache 以允许用户通过 https 访问 api?
- swift - 来自 VNDetectRectangleRequest 的边界框被绘制在 ImageView 上的错误位置
- annotations - 专门使用注释进行绘图时出错
- typescript - 如果存在特定值,如何删除对象键数组中的其他值?
- c# - 如何使用 appium 测试使用 wpf 创建的菜单
- php - 如何在 PHP 中获取从对话框流到 API 的自定义有效负载响应
- java - 如何使用 apache poi 从绘制的图中获取 getMajorUnit 值