Hey everyone,
I'm doing some simple stuff, so hopefully this question can be easily answered easily. I'm using gcc to compile. The push works perfectly fine. The problem is the pop. I get a segmentation fault whenever I compile and run it.
Here are the pop and push functions:
int push(stack *stk, int data)
{
stk->head = makeNode(data, stk->head);
stk->length += 1;
return data;
}
int pop(stack *stk)
{
//Returns popped item
//Returns -1 if stack length is zero
if (stk->length < 1)
{
printf("No items to pop.");
return -1;
}
int data = stk->head->value;
struct node *toBeFreed = stk->head;
stk->head = stk->head->ptr;
free(toBeFreed);
stk->length -= 1;
return data;
}
I honestly don't know what the problem is, because the code is similar. I reassign the head variable in the stack in the push function, but it causes errors in the pop function. The assignment to data also gives me a seg fault. Pretty much everything except for the return and stack length assignment statements give me segmentation faults. Can any of you help me figure this out? What is causing these seg faults?
Here is the entire program:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int value;
struct node *ptr;
};
struct node *makeNode(int value, struct node *ptr)
{
struct node *newNode = malloc(sizeof(struct node));
newNode->value = value;
newNode->ptr = ptr;
return ptr;
}
typedef struct stack
{
struct node *head;
int length;
} stack;
stack makeStack()
{
stack stk;
stk.head=NULL;
stk.length = 0;
return stk;
}
int push(stack *stk, int data)
{
stk->head = makeNode(data, stk->head);
stk->length += 1;
return data;
}
int pop(stack *stk)
{
if (stk->length < 1)
{
printf("No items to pop.");
return -1;
}
int data = stk->head->value;
struct node *toBeFreed = stk->head;
stk->head = stk->head->ptr;
free(toBeFreed);
stk->length -= 1;
return data;
}
int main()
{
stack s = makeStack();
printf("Pushing ints one through five. Should display ints one through five on separate lines: \n");
int i;
for (i = 1; i <= 5; i++)
printf("%d\n",push(&s, i));
printf("Popping ten values. Should display ints one through five in reverse order on separate lines along with 5 error statements.\n");
for (i = 0; i <= 10; i++)
printf("%d\n",pop(&s));
return 0;
}