c - 如何在链表中正确执行弹出功能?
问题描述
我在我的程序上运行了 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)
解决方案
您的pop
函数没有提供任何方法将新值返回head
给调用者。所以在你的循环中,循环中的第二次,head
仍然指向你在循环中第一次释放的对象。
请注意,不是传递head
, to push
,而是传递指向函数的指针?这样,可以修改. 对 .做同样的事情。head
push
push
head
pop
void pop (linkedPtr hd)
{
linkedPtr tmp = hd;
hd = hd->next; // This line doesn't do anything
free (tmp);
}
注意标记的行是如何修改的hd
,但在完成hd
时即将超出范围pop
。没有处理 的新值hd
。
推荐阅读
- spring-boot - 新的 Spring 2.4.0 Data Rest 项目报告不符合所有 BeanPostProcessor 处理的条件
- javascript - 如何在 JQuery Datepicker 中调整下一个和上一个按钮的大小?
- python-3.x - 强制客户端等待来自 azure 函数的响应
- python - 如何过滤数据框中的行以仅获取 3 个最受欢迎的数据并删除其他未使用的数据?
- r - 如何在 R 中将 MM/DD/YY 转换为 YYYY-MM-DD?
- javascript - onChange 事件影响字符串长度(消毒剂)
- oauth-2.0 - Google G Suite 用户的密码验证
- c# - 如何获得单选按钮的价值?
- android-layout - 当按钮内还有这么多空间时,为什么右边的文本被剪掉了?
- python - 获取字符串中的所有表情符号