首页 > 解决方案 > 分段错误: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;


        }
    }
}

标签: c

解决方案


这个

     scanf(..., name);

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

这同样适用于本声明

    scanf(..., name2);

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


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

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


推荐阅读