为什么我的链表仅打印最后一个条目?

时间:2019-12-21 22:30:42

标签: c linked-list

由于我处于循环状态,因此我试图向用户询问一个单词,然后将其保存在链接列表中。问题是它只会打印我的最后一个单词,而不是我一个接一个地介绍的所有单词。我在做什么错了?

我的主要想法并不完全是这样,因为自从使用线程以来,我有很多代码,但是我100%确信问题出在我发布的代码上。

编辑

typedef struct data_msg msg, *p_msg;
struct data_msg {
    char topic[50];
    char title[50];
    char body[1000];
    int duration;
    p_msg next;
};

p_msg save_msg(p_msg pm, char topic[50], char title[50], char body[1000]){

    p_msg new, aux;

    new = malloc(sizeof(msg));

    if(new == NULL){
        printf("\n[ERROR] Memory allocation.");
        exit(0);
    }

    strcpy(new->topic, topic);
    strcpy(new->title, title);
    strcpy(new->body, body);
    new->next = NULL;

    if(pm == NULL)
        pm = new;
    else{
        aux = pm;
        while(aux->next != NULL)
            aux = aux->next;
        aux->next = new;
    }

    free(new);

    return pm;
}

int main(){
      char topic[50], title[50], body[1000];
        p_msg list = NULL;

        do{
            scanf("%s", topic);

            list = save_msg(list, topic, title, body);  

        } while(strcmp(topic, "exit") != 0);

    while(list != NULL){
                printf("=> %s\n", list->topic);
                list = list->next;
        }

    return 1;

1 个答案:

答案 0 :(得分:0)

问题在于您正在释放仍在使用的内存!

pmessage armazena_msg(pmessage pm, char *topic, char *title, char *company){

    pmessage new = malloc(sizeof(message));

    // populate this new item, copy things in

    // now link into the linked list
    if(pm == NULL)
        pm = new;
    else{
        pmessage tmp = pm;
        while(tmp->next != NULL)
            tmp = tmp->next;
        tmp->next = new;
    }

//  free(new);      // BOOM!

    return pm;
}

您返回的pm始终包含您分配和初始化的内存,如果是第一个内存,则直接包含该内存,也可以将其初始化,或者挂钩到列表中,但是当您释放它时,该内存将返回给操作系统。

然后在 second 调用中,很有可能再次返回原始内存-为您精心设置的原始内存-因此列表最终指向自身。

注释free(),它应该可以按您期望的那样工作。

编辑,仍然可能存在一个错误:我认为您应该先将exit链接到列表中,然后再将消息链接到列表中,除非您也想将"exit"确实添加到列表中