c - 分段错误:findPerson 的结构函数不起作用
问题描述
所以我被要求开发一个制作家谱的程序。作为首先要做的功能之一,是一个功能,用于查找输入名称是否已添加到人员。我的 add 函数工作正常,但是当我尝试使用 findPerson 函数时,我收到 Segmentation Fault (core dumped) 的错误。
#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 left\n");
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 unknown\n");
}
}
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("bye\n");
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]"
。
推荐阅读
- excel - VBA 更改值,调用宏。忽视
- c# - 在 Visual Studio 中创建项目时如何自动添加其他库?
- php - 防止前端表单按钮重定向到 admin-post.php
- rust - 如何使用循环下降并插入 Rust 中的二叉树?
- c - 为什么我在 C 程序中没有得到正确的输出?
- ssl - cloudfare 上的 ssl 在浏览器上显示“您的连接不是私有的”
- xcode9.3 - OCLint Xcode 9.3.1 失败
- javascript - jQuery 事件委托行为
- jenkins - Jenkins groovy 管道发现价值
- python - 运行 tkinter+pymysql 脚本时出现 pymysql.err.ProgrammingError