在C语言中使用free()时出现堆损坏错误

问题描述 投票:0回答:2

今天我试图在C语言中使用Linked List实现一个Stack,一切都很好,直到我创建了一个使用free的pop函数,一旦我调用free函数,我的程序就崩溃了,然后Visual Studio在一个新的窗口中抛出了Heap Corruption Error信息。除了这个函数,其他所有的函数都能正常工作,我只是不明白发生了什么。谢谢大家的回答。

这是我的代码。

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

struct Node {
    char data;
    struct Node *next;
};

void push(struct Node **top, char data) {

    struct Node *temp = (struct Node *)malloc(sizeof(struct Node *));

    if (temp == NULL) {
        printf("Stack overflow.\n");
    } else {
        temp->data = data;
        temp->next = *top;
        (*top) = temp;
    }
}

void pop(struct Node **top) {

    struct Node *aux;

    if (*top != NULL) {
        printf("Popped element: %c\n", (*top)->data);
        aux = *top;
        *top = (*top)->next;
        free(aux);
    } else {
        printf("Stack is empty");
    }
}

void display(struct Node *top) {

    struct Node *aux = top;

    while (aux != NULL) {
        printf("%c ", aux->data);
        aux = aux->next;
    }

    printf("\n");
}

int main() {

    struct Node *root = NULL;
    push(&root, 'a');
    push(&root, 'b');
    push(&root, 'c');
    printf("Stack:\n");
    display(root);

    pop(&root);
    printf("\nStack:\n");
    display(root);

    return 0;
}
c linked-list stack heap-memory free
2个回答
4
投票

你在这一行中只为一个指针分配了缓冲区。

struct Node *temp = (struct Node *)malloc(sizeof(struct Node *));

在典型的环境中,结构体的大小会比指针大,所以分配的内存不会有足够的大小。

这一行应该是

struct Node *temp = malloc(sizeof(struct Node));

struct Node *temp = malloc(sizeof(*temp));

注意事项 c - 我是否要投递 malloc 的结果?- 堆栈溢出


0
投票

你可能想这样做。

struct Node *temp = (struct Node *)malloc(sizeof(struct Node));

而不是:

struct Node *temp = (struct Node *)malloc(sizeof(struct Node *));
© www.soinside.com 2019 - 2024. All rights reserved.