首页 > 解决方案 > 如何在链表中正确执行弹出功能?

问题描述

我在我的程序上运行了 GDB,我认为我的 pop 函数有问题,但我不完全确定我在该函数中的逻辑有什么问题?

一切似乎都很好地推入了堆栈,但是当我们开始从堆栈中弹出值时,您可以看到程序失败。

我为链表的头部创建了一个临时 ptr,然后将链表的头部设置为下一个节点,然后释放我的临时指针。

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

#define SIZE 10
#define FALSE 0
#define TRUE  1

struct linkedStruct {
    int elem;
    struct linkedStruct *next;
};
 
typedef struct linkedStruct linked;
typedef linked *linkedPtr; 

void push(linkedPtr *hd, int val) {
    linkedPtr ptr = (linkedPtr)malloc(sizeof(linked));
    ptr->elem = val;
    ptr->next = *hd;
    *hd = ptr;
}

int isEmpty(linkedPtr hd) {
    if (hd == NULL)
        return TRUE;
    else
        return FALSE;
}
 
int top(linkedPtr hd) {
    return (hd->elem);
}

void pop(linkedPtr hd) {
    linkedPtr tmp = hd;
    hd = hd->next;
    free (tmp);
}

void show(linkedPtr hd) {
    while (hd != NULL) {
        printf("%d, ", hd->elem);
        hd = hd->next;
    }
    printf("\n");
}

int main(int argc, char **argv) {
    linkedPtr head = NULL;
    int i;
    int temp;

    /* push 10 random values onto the stack showing the stack growing */
    for (i = 0; i < SIZE; ++i) {
        temp = rand() % 100;
        printf("In main(): temp: %6d\n", temp);
        push(&head, temp);
        show(head);
   }

   printf("\n");

   /* remove the value from the stack */
   while (!isEmpty(head)) {
       printf("Top of stack value is: %d\n", top(head));
       pop(head);
   }
}

输出

In main(): temp:     83
83, 
In main(): temp:     86
86, 83, 
In main(): temp:     77
77, 86, 83, 
In main(): temp:     15
15, 77, 86, 83, 
In main(): temp:     93
93, 15, 77, 86, 83, 
In main(): temp:     35
35, 93, 15, 77, 86, 83, 
In main(): temp:     86
86, 35, 93, 15, 77, 86, 83, 
In main(): temp:     92
92, 86, 35, 93, 15, 77, 86, 83, 
In main(): temp:     49
49, 92, 86, 35, 93, 15, 77, 86, 83, 
In main(): temp:     21
21, 49, 92, 86, 35, 93, 15, 77, 86, 83, 

Top of stack value is: 21
Top of stack value is: 0
Top of stack value is: 17254288
Top of stack value is: 17254288
Top of stack value is: 17254288
Top of stack value is: 17254288
Top of stack value is: 17254288
Top of stack value is: 17254288
Top of stack value is: 0
double free or corruption (fasttop)

标签: c

解决方案


您的pop函数没有提供任何方法将新值返回head给调用者。所以在你的循环中,循环中的第二次,head仍然指向你在循环中第一次释放的对象。

请注意,不是传递head, to push,而是传递指向函数的指针?这样,可以修改. 对 .做同样的事情。headpushpushheadpop

void pop (linkedPtr hd)
{
 linkedPtr tmp = hd;
 hd = hd->next; // This line doesn't do anything
 free (tmp);
}

注意标记的行是如何修改的hd,但在完成hd时即将超出范围pop。没有处理 的新值hd


推荐阅读