I was trying to implement stack with linked list implementation but seems to encounter 'segmentation error' . The code seems to compile and also run but when I actually enter the value of 'times' int variable in the stdin. The code shows segmentation error. The scanf also doesn't show the formatted string.
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define NAME_MAX 40
struct NODE{
char name[NAME_MAX];
int regno;
int age;
struct NODE* next;
};
struct STACK{
struct NODE *head;
int size;
};
void printStack(const struct STACK *stack);
bool pushStack(struct STACK *stack);
bool makeStack(struct STACK *stack, int data_count);
void cleanStack(struct STACK *stack);
int main(){
struct STACK list = {NULL,0};
int times = 0;
scanf("How many data you want to enter: %d", ×);
if(!makeStack(&list, times)){
fprintf(stderr, "Stack wasn't created\n");
}
printStack(&list);
cleanStack(&list);
return 0;
}
void cleanStack(struct STACK *stack){
struct NODE *trav = stack->head;
while(trav!=NULL){
struct NODE *temp = trav;
trav = trav->next;
temp = NULL;
}
}
void printStack(const struct STACK *stack){
struct NODE *trav = stack->head;
for(int counter=1; stack!=NULL; trav=trav->next,++counter,++stack){
printf("%d: %s %d %d",counter,trav->name,trav->regno, trav->age);
}
}
bool makeStack(struct STACK *stack, int data_count){
while(data_count--){
if(!pushStack(stack)){
return false;
}
}
return true;
}
bool pushStack(struct STACK *stack){
struct NODE *temp = malloc(sizeof(struct NODE));
if(temp==NULL) return false;
scanf("Input Name: %s", temp->name);
scanf("Input RegNo: %d", &temp->regno);
scanf("Input age: %d", &temp->age);
temp->next = stack->head;
stack->head = temp;
++stack->size;
return true;
}