Reputation: 15
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct node
{
char data;
struct node* link;
} STACK_NODE;
void insert(STACK_NODE** p);
void print(STACK_NODE** p);
bool push(STACK_NODE** p, char in);
bool pop(STACK_NODE** p, char* out);
int main()
{
STACK_NODE* myStackTop;
insert(&myStackTop);
print(&myStackTop);
return 0;
}
void insert(STACK_NODE** p)
{
char mychar;
int NC,k;
bool Mem;
printf("how many charachters do you want to put in stack:");
scanf("%d",&NC);
for(k=0;k<NC;k++)
{
printf("enter character:-");
scanf(" %c",&mychar);
Mem=push(p,mychar);
if(!Mem)
{
printf("ran out of memory or unknown error");
exit(100);
}
}
}
bool push(STACK_NODE** p,char c)
{
STACK_NODE* newNode;
bool success;
newNode = (STACK_NODE*)malloc(sizeof(STACK_NODE));
if(!newNode)
{
success = false;
}
else
{
newNode->data=c;
newNode->link=*p;
*p=newNode;
success = true;
}
return success;
}
void print(STACK_NODE** p)
{
char out;
printf("contents of the stack:");
while(pop(p,&out))
{
printf("%c",out);
}
return;
}
bool pop(STACK_NODE** p,char* c)
{
STACK_NODE* Ndel;
bool success;
if(*p)
{
success = true;
*c=(*p)->data;
Ndel= *p;
*p = (*p)->link;
}
else
success = false;
return success;
}
whole program works fine until the last element is popped from the stack and printed . the program crashes after the last character is printed. I tried debugging it by placing additional statements in the print() method definition after the while block. i think the problem is with the if(*p) statement in the pop() function definition. I checked for solutions. But nothing worked.
Upvotes: 1
Views: 59
Reputation: 44274
You need to initialize your stack to NULL
int main()
{
STACK_NODE* myStackTop = NULL;
If you don't, you'll use an uninitialized value when you pop
the last element.
BTW: In pop
it seems you forgot a free(Ndel);
Upvotes: 2