so I'm trying to build a stack in C, using pointers and malloc.
My stack.h has a struct
typedef struct
{
int *top;
int *prev;
} intstack_t;
I'm initialising the stack like this:
int stackInit(intstack_t* self) {
if(malloc(sizeof(self != NULL))) {
self->top = malloc(sizeof(self->top));
self->prev = malloc(sizeof(self->prev));
return 0;
} else {
return 1;
}
}
void stackPush(intstack_t* self, int i) {
self->prev = self->top;
self->top = newElement(i);
}
int stackPop(intstack_t* self) {
int tmp = *self->top;
free(self->top);
self->top = self->prev;
return tmp;
}
int *newElement(int i) {
int *new = malloc(sizeof(i));
*new = i;
return new;
}
My main:
int main()
{
intstack_t stack;
stackInit(&stack);
stackPush(&stack, 1);
stackPush(&stack, 2);
stackPush(&stack, 3);
stackPop(&stack);
printf("stackTop: %i \n", stackTop(&stack));
stackPop(&stack);
printf("stackTop: %i \n, stackTop(&stack));
}
While I can push onto the stack, only the first pop yields the desired output. When I pop again the result is something completely different.
stackTop: 0
stackTop: 1
stackTop: 2
stackTop: 3
stackTop: 2
stackTop: 34792624
Could someone please point me in the right direction, as I dont see where I'm going wrong?
if(malloc(sizeof(self != NULL)))why are you not saving the return value ofmalloc()somewhere? At minimum you'd need tofree()that later.mallocs that your code has, I'm guessing the latter.)