Im trying to implement my own stack program, but when I initialize the stack I get the SEGMENTATION FAULT!
extern int stackInit(intstack_t* self){
self = malloc(sizeof(intstack_t));
if(self == NULL){
fprintf(stderr,"Out of memory.");
free(self);
exit(-1);
}
self->bottom = malloc(MINIMUM_SIZE * sizeof(int));
if(self->bottom == NULL){
fprintf(stderr,"Out of memory.");
free(self->bottom);
exit(-1);
}
self->top = self->bottom - 1;
self->allocated_top = self->bottom + MINIMUM_SIZE -1;
return 0;
}
int main()
{
intstack_t stack;
stackInit(&stack);
stackPush(&stack, 1);
stackPush(&stack, 2);
stackPush(&stack, 3);
}
extern void stackPush(intstack_t* self, int i){
//check if the stack is full and double its size if so.
if(self->top == self->allocated_top){
ptrdiff_t total = self->top - self->bottom +1;
ptrdiff_t new_total = GROWTH_FACTOR + total;
self->bottom = realloc(self->bottom, new_total * sizeof(int));
if(self->bottom == NULL){
fprintf(stderr,"Out of memory.");
free(self->bottom);
exit(-1);
}
self->top = self->bottom + total - 1;
self->allocated_top = self->bottom + new_total - 1;
}
*(++self->top) = i;
}
and here is the struct:
typedef struct
{
int* bottom;
int* top;
int* allocated_top;
} intstack_t;
and when I compile it with valgrind I get this: Use of uninitialised value of size 8 ==2744731== at 0x4008B2: stackPush (in /vol/fob-vol2/mi16/sajoseig/Compilerbau/lab1/stack) ==2744731== by 0x4009AB: main (in /vol/fob-vol2/mi16/sajoseig/Compilerbau/lab1/stack) ==2744731== Uninitialised value was created by a stack allocation ==2744731== at 0x400987: main (in /vol/fob-vol2/mi16/sajoseig/Compilerbau/lab1/stack)
==2744731== Conditional jump or move depends on uninitialised value(s) ==2744731== at 0x4007C5: stackPush (in /vol/fob-vol2/mi16/sajoseig/Compilerbau/lab1/stack) ==2744731== by 0x4009AB: main (in /vol/fob-vol2/mi16/sajoseig/Compilerbau/lab1/stack) ==2744731== Uninitialised value was created by a stack allocation ==2744731== at 0x400987: main (in /vol/fob-vol2/mi16/sajoseig/Compilerbau/lab1/stack)
==2744731== Process terminating with default action of signal 11 (SIGSEGV): dumping core ==2744731== Bad permissions for mapped region at address 0x4005F4 ==2744731== at 0x4008B2: stackPush (in /vol/fob-vol2/mi16/sajoseig/Compilerbau/lab1/stack) ==2744731== by 0x4009AB: main (in /vol/fob-vol2/mi16/sajoseig/Compilerbau/lab1/stack)