首页 > 解决方案 > 为什么我的链表插入函数在使用 scanf 输入字符串时会出现分段错误?

问题描述

我是一名算法学生,试图以字母顺序来实现一个带有单词的链表。问题是,当我使用 scanf 获得输入并将其传递给函数时,它会出现分段错误。我试过直接传递字符串,效果很好。

这是代码:

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

typedef struct NOH {
    char *palavra; 
    struct NOH *next; 
    struct NOH *prev; 
}NOH;

typedef struct LISTA {
    NOH *head;
}LISTA;

void *cria_lista(){
    LISTA *new_lista = (LISTA*) malloc(sizeof(LISTA));
    new_lista -> head = NULL;

    return new_lista;
}

void insere_lista(LISTA *lista, char *palavra){
    NOH *new_node = (NOH*) malloc(sizeof(NOH));
    new_node -> palavra = palavra;

    if(lista -> head == NULL){
        lista -> head = new_node;
        new_node -> next = NULL;
        new_node -> prev = NULL;
    } else {

        if(strcmp(palavra, lista -> head -> palavra) < 0){ 
            new_node -> prev = NULL;
            new_node -> next = lista -> head;
            lista -> head -> prev = new_node;
            lista -> head = new_node;
        } else {

            NOH *aux = lista -> head;
            while(strcmp(palavra, aux -> palavra) > 0 && aux -> next != NULL)
                aux = aux -> next;

            if(aux -> next == NULL && strcmp(palavra, aux -> palavra) > 0){ 
                new_node -> next = NULL;
                new_node -> prev = aux;
                aux -> next = new_node;
            } else { //se tiver que ser inserido no meio
                new_node -> next = aux;
                new_node -> prev = aux -> prev;
                aux -> prev -> next = new_node;
                aux -> prev = new_node;
            }
        }
    }
}

void printa_lista(LISTA *lista){
    NOH *aux = lista -> head;
    if(aux == NULL)
        printf("lista vazia!\n");
    else {
        while(aux -> next != NULL){
            printf("%s -> ", aux -> palavra);
            aux = aux -> next;
        }
        printf("%s\n", aux -> palavra);
    }
}

int main(){
    char word[100];

    LISTA *L = cria_lista();

    scanf("%s", word);
    insere_lista(L, word); //using "teste" as word
    printa_lista(L);

    scanf("%s", word); 
    insere_lista(L, word); //using "testee" as word
    printa_lista(L);

    return 0;
}

我尝试使用 gdb 来查找分段错误的位置,这是判决:

Program received signal SIGSEGV, Segmentation fault.
0x000055555555498a in insere_lista (lista=0x555555756260, 
    palavra=0x7fffffffde20 "testee") at lista_encadeada.c:51
51                  aux -> prev -> next = new_node;

使用以下代码作为主要代码似乎有效:

int main(){
    char word[100];  
    LISTA *L = cria_lista();

    insere_lista(L, "macaco");
    printa_lista(L);

    insere_lista(L, "avestruz");
    printa_lista(L);

    insere_lista(L, "elefante");
    printa_lista(L);

    insere_lista(L, "cavalo");
    printa_lista(L);

    insere_lista(L, "zebra");
    printa_lista(L);

    insere_lista(L, "hipopotamo");
    printa_lista(L);

    return 0;
}

顺便说一句,我是巴西人,很抱歉我的英语和我的葡萄牙语代码,如果太麻烦我可以尝试用英语重写它。

标签: cstringfunctionlinked-list

解决方案


推荐阅读