【发布时间】:2021-01-22 03:24:59
【问题描述】:
我在我的程序上运行了 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)
【问题讨论】:
-
您可能还想查看:Is it a good idea to typedef pointers?。 (回答..不)
-
我不禁想知道你是如何得到
push正确和pop错误的
标签: c