i tired to implement a stack using a linked list, so i did it as global and i made some stack functions (push, pop, isempty) isempty and push work great, but i got problem with pop function, well basiclly it work to but i dont know why when i try to free the memory of the node i poped (after saving the data), its not working and cause an error. if i just delete the line of "free" in pop function it work great but you know the problem here i have to free the heap memory after using it... so what can i do?
there is some of the code:
#include <stdio.h>
#include <stdlib.h>
struct stack
{
int data;
struct stack* next;
};
struct stack* top = NULL; ///stack is global, so push and pop can use it.
int isEmpty()
{
if (top == NULL)
return 0;
else return 1;
}
void push(int x)
{
struct stack* temp = (struct stack*)malloc(sizeof(struct stack*));
if (temp == NULL)
{
printf("Error! no allocation!!");
return;
}
temp->data = x;
temp->next = top;
top = temp;
}
int pop()
{
struct stack* temp;
if (isEmpty() != 0)
{
temp = top;
int x = top->data;
top = top->next;
free(temp);
return x;
}
else
{
printf("stack is empty nothing to pop");
return -1;
}
}
int main()
{
push(1);
push(2);
push(3);
push(4);
push(5);
push(6);
push(7);
int cur;
while (isEmpty())
{
cur = pop();
printf("|%d|--->", cur);
}
printf("\n");
return 0;
}