confusion about free(pointer) in c -
i trying implement stack using pointers, structure definition in code below. called push()
function 3 elements (say: 2, 4, 6) insert. then, call function display()
. it's showing 0
. figured out reason because of free()
function in push()
function. but, don't know indeed happening there. should not use free()
free allocated memory used temp
in 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 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); }
void push(){ int ele; struct stack *temp,*p; printf("entere 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); // don't free temp here ! }
you have free pointer if don't need more. think case, since don't use temp
, doesn't. parameter of free
valid memory address. temp
valid memory address, you're assigning temp
start
! : free(tmp)
same free(start)
, , that's not want.
Comments
Post a Comment