I am trying to implement a stack using pointers, the structure definition is in the code below. I called the push()
function for three elements (say: 2, 4, 6) to insert. Then, I call the function display()
. It's showing only 0
. I figured out the reason was because of the free()
function in my push()
function. But, i don't know what indeed is happening there. Should I not use free()
to free the allocated memory used by temp
in my code? If so, why?
#include<stdio.h>
//#include<unistd.h>
#include<stdlib.h> // malloc ,calloc, free avail here
void push();
void pop();
void display();
struct stack {
int data;
struct stack *next;
};
struct stack *start = NULL;
void push()
{
int ele;
struct stack *temp, *p;
printf("entere the element\n");
scanf("%d", &ele);
temp = (struct stack *) malloc(sizeof(struct stack));
temp->data = ele;
if (start == NULL) {
start = temp;
start->next = NULL;
} else {
p = start;
while (p->next != NULL) {
p = p->next;
}
p->next = temp;
temp->next = NULL;
}
free(temp);
}