我正在为我当前的CS类编写一个涉及链表的程序,当我调用它时,其中一个函数特别会导致分段错误。函数如下:
void addSong(Playlist *theList, char *name, char *title, char *artist, int minutes, int seconds) {
/*
1. Make sure a playlist by that name exists (so you can add a song to it)
2. Make sure the song does not already exist in the playlist (title/artist)
3. Add the new song to the end of the songlist in that playlist (add-at-end)
*/
Playlist *Pointer = theList;
while(1){//Find the list
if(strcmp(Pointer->name, name) == 0)
break;
if(Pointer->next == NULL){
printf("There is no playlist by that name.n");
return;
}
Pointer = Pointer->next;
}
Song *playPoint = Pointer->songlist;
while(1){//Find the end of the list
if(playPoint == NULL){
Song *Songy = malloc(sizeof(Song));
Songy->title = title;
Songy->artist = artist;
Songy->minutes = minutes;
Songy->seconds = seconds;
Pointer->songlist = Songy;
}
if(strcmp(playPoint->title, title) == 0 && strcmp(playPoint->artist, artist) == 0){
printf("There is already a song by that title and artist.");
return;
}
if(playPoint->next == NULL){
break;
}
playPoint = playPoint->next;
}
Song *Songy = malloc(sizeof(Song));
Songy->title = title;
Songy->artist = artist;
Songy->minutes = minutes;
Songy->seconds = seconds;
playPoint->next = Songy; //Add the song to the end of the list
return;
}
如果有关系,下面是引用的两个结构体:
typedef struct song {
char *title;
char *artist;
int minutes;
int seconds;
struct song *next;
} Song;
typedef struct playlist {
char *name;
Song *songlist;
struct playlist *next;
} Playlist;
我做了什么导致段故障?
您没有发布足够的信息,以使某人能够准确地发现您的段错误发生的位置。考虑在MCVE示例中隔离它。
然而,当playPoint == NULL
在第二个while循环中时,肯定会发生段故障,因为您最终通过访问playPoint->title
来使用它:
if(playPoint == NULL){
Song *Songy = malloc(sizeof(Song));
Songy->title = title;
Songy->artist = artist;
Songy->minutes = minutes;
Songy->seconds = seconds;
Pointer->songlist = Songy;
}
// here, playPoint is still equal to NULL!! COde from your if statement did not change that!
// accessing playPoint->title and playPoint->artist will crash for sure (seg fault)
if(strcmp(playPoint->title, title) == 0 && strcmp(playPoint->artist, artist) == 0){
printf("There is already a song by that title and artist.");
return;
}
你的意思可能是:
if(playPoint == NULL){
playPoint = malloc(sizeof(Song));
playPoint->title = title;
playPoint->artist = artist;
playPoint->minutes = minutes;
playPoint->seconds = seconds;
Pointer->songlist = playPoint;
}
但是很难猜测…
但是在这段代码中可能有其他来源的段错误(如Songy->next未设置,如Ryan注释)+在其他代码中您没有发布
您可能在开始测试之前编写了太多代码,并且可能有很多地方做错了,从而导致隔离错误。考虑重新从头开始您的项目,并通过迭代(测试和验证每个迭代)....添加内容或者使用调试器来修复它们…