分割错误:查找人员的结构函数不起作用



所以我被要求开发一个制作家谱的程序。作为第一个要做的函数之一,是一个查找输入名称是否已添加到人员的函数。我的添加函数工作正常,但是当我尝试使用 findPerson 函数时,出现分段错误(核心转储(。

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

typedef struct _person {
char *name;
int birth;
struct _person *nextperson;// pointer to the next person structure on
struct _person *mother; //mother pointer to another person structure
struct _person *father;//father pointer to another person structure
} person;
void addperson (person **families, char *name, int birthyear)
{
person *newperson;
if (strcmp(name,"unknown")!=0) {
newperson=(person *)malloc(sizeof(person));//allocate space for the n
if (newperson==NULL) {
printf("insert: error: no space leftn");
return;
}
//make space for newperson's name, the lenght of the input name
newperson->name =(char *)malloc(sizeof(char)*(strlen(name) + 1));
strcpy(newperson->name, name);//copy the input argument name to the
newperson->birth=birthyear;
newperson->nextperson=*families;
newperson->mother=NULL;
newperson->father=NULL;
return;
} else {
printf("A person can not be called unknownn");
}
}
person *findperson (person *families, char *person)
{
struct _person *finder= families;
// finder =(person *)malloc(sizeof(person));
//finder=families;
if(strcmp(finder->name,person)==0) {
return finder;
} else {
if (finder->nextperson!=NULL) {
finder=finder->nextperson;
findperson(finder, person);
} else {
printf("Person %s not found",person);
}
}
}
void main(){
person *families= NULL; //initializ list with 0
char*name,*name2;
char command;
person * foundPerson;
int birth;
int loop=1;
while(loop==1){
printf("command?");
scanf(" %c", &command);
switch(command){
case 'q':
printf("byen");
loop=2;
break;
// case 'n':
//  break;
case 'i':
printf("name? ");
scanf(" %[^n]s", name);
printf("birthyear? ");
scanf(" %d", &birth);
addperson(&families, name, birth);
break;
case 'f':
printf("name? ");
scanf(" %[^n]s", name2);
foundPerson=  findperson(families,name2);
printf("NAME FOUND: %s",foundPerson->name);
break;
default:
break;

}
}
}

scanf(..., name);

将输入扫描到name指向的位置。name不会初始化为指向任何位置,因此扫描程序会扫描到无效内存中,并通过这样做调用未定义的行为。从那以后,任何事情都可能发生。程序可能会立即或稍后崩溃或不崩溃。

这同样适用于此声明

scanf(..., name2);

更多关于这个不幸看似常见的错误在这里。


除了上述问题之外,此" %[^n]s"不是您所期望的。当它读取一个字符串然后等待s时。

它应该只是" %[^n]".

最新更新