Home > Enterprise >  Stack implementation is giving Segfault
Stack implementation is giving Segfault

Time:11-13

I am currently writing my own virtual machine. I have to implement the stack. For whatever reason whenever I call sienna_stack_push(processor->stack, 0); it gives me a segfault.

here is the implementation of the stack

#include <stdlib.h>
#include <stdio.h>
#include "stack.h"

// Helper functions

int is_empty(sienna_stack_t* stack){
    return stack->top == -1;
}

int is_full(sienna_stack_t* stack){
    return stack->top == stack->max_size;
}

void sienna_stack_init(sienna_stack_t* stack, int capacity){
    stack = (sienna_stack_t*)malloc(sizeof(sienna_stack_t));
    stack->max_size = capacity;
    stack->top = -1;
    stack->items = (int*)calloc(capacity, sizeof(int));

}

void sienna_stack_push(sienna_stack_t* stack, int value){
    if(is_full(stack)){
        printf("FATAL: Stack overflow!\n");
        exit(-1);
    }
    stack->items[  stack->top] = value;
}

int sienna_stack_pop(sienna_stack_t* stack){
    if(is_empty(stack)){
        printf("FATAL: Stack underflow!\n");
        exit(-1);
    }
    return stack->items[stack->top--];
}

int sienna_stack_peek(sienna_stack_t* stack){
    return stack->items[stack->top];
}

here is the stack struct definition

typedef struct {
    int max_size;
    int top;
    int* items;
} sienna_stack_t;

here is me using it

#include <stdio.h>
#include "stack.h"

int main() {
    sienna_stack_t stack;
    sienna_stack_init(&stack, 0xFFFF);
    sienna_stack_push(&stack, 0);
}

and the error is saying it is happening when calling sienna_stack_push();

CodePudding user response:

I guess, you want to reserve sizeof(int) * capacity bytes of memory, but in reality you reserve nothing, because the first parameter of calloc() is 0. Thus, you want to access non-reserved memory, that leads to a crash.

EDIT

Your initialisation is wrong. stack is a static variable. When you call init, you pass the address of this variable. Now you assign an new (anonymous) variable that get lost. You could change stack into a pointer variable:

void sienna_stack_init(sienna_stack_t** stack, int capacity){
   *stack = (sienna_stack_t*)malloc(sizeof(sienna_stack_t));
   (*stack)->max_size = capacity;
   (*stack)->top = -1;
   (*stack)->items = (int*)calloc(capacity, sizeof(int));
}
 
// ...

int main(int argc, char *argv[]){
   sienna_stack_t *stack;
   sienna_stack_init(&stack, 0xFFF);
   sienna_stack_push(stack, 0);
}
  • Related