Search code examples
clinked-liststackheap-memoryfree

Heap Corruption Error when using free() in C


Today I was trying to implement a Stack using Linked List in C, everything was fine until I created a pop function which uses free, once I call the free function my program crashes and then Visual Studio throws Heap Corruption Error message in a new window. All the other functions are working fine except this one, I just can't figure out what's happening. Thanks for all your answers.

Here's my code:

#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;
}

Solution

  • You allocated only buffer for a pointer in this line

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

    In typical environment, size of the structure will be larger than the pointer, so allocated memory won't have enough size.

    The line should be

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

    or

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

    Note: c - Do I cast the result of malloc? - Stack Overflow