0

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;
}
  • `struct Node *temp = (struct Node *)malloc(sizeof(struct Node *));` is wrong, write `struct Node *temp = malloc(sizeof(*temp));` instead – Felix G May 04 '20 at 13:29

2 Answers2

5

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

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

You probably wanted to do this:

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

instead of:

struct Node *temp = (struct Node *)malloc(sizeof(struct Node *));
mar
  • 154
  • 7