Alcore Alcore - 1 month ago 9
C Question

Stack with a dynamic array: segfaults when popping value multiple times

I have a stack implemented with a dynamically allocated array, which is populated using scanf(). The push function works properly, except that when I print out the stack, I always get two extra zeros at the beginning of the output. Attempting to pop the stack only pops the zeroes, and it segfaults once the popping happens twice. I can't figure out where this issue is occurring.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*Creates struct of stack*/
typedef struct Stack{
int *ptArray;
int top;
int stackSize;
int itemsInStack;
} Stack;

/*Initialized stack*/
Stack* stackInit(){
Stack *a;
a= (Stack*) malloc(sizeof(Stack));
a-> ptArray=(int*) malloc(sizeof(int)) ;
a-> top=0;
a-> stackSize=1;
return a;
}

void stackPush( Stack *stx, int val){

if( (stx->top) == (stx->stackSize)){
grow(&stx->ptArray, &stx->stackSize);
}
stx->ptArray[stx->top]= val;
stx->top++;
stx->itemsInStack++;
}
/*Grows astack array when space runs out*/
void grow(int** array, int *sz){
int *temp;
temp= (int*) malloc(sizeof(int)* (*sz+2) );
int i;
for( i=0; i< *sz; i++)
temp[i]=( *array)[i];
free(*array);
*array= temp;
*sz=*sz+2;
}

void stackPop( Stack* stx){
free(stx->ptArray[stx->top]);
stx->top--;
stx->stackSize--;
stx->itemsInStack--;

}

void showStack(Stack* s){
int i;
printf("\n");
for(i=s->stackSize; i>-1; i--){
printf("%d\n", s->ptArray[i]);
}
}

void main(int argc, char** argv){

Stack *stackArray;
stackArray= stackInit();

int val=0;
while (val != -999) {
scanf("%d", &val);
if (val == -999) {
break;
}
stackPush(stackArray, val);
}

showStack(stackArray);
stackPop(stackArray);
stackPop(stackArray);
showStack(stackArray);
stackPop(stackArray);
showStack(stackArray);

}

Answer

You have a problem in your malloc / free couples.

You allocate the array like this :

 a-> ptArray=(int*) malloc(sizeof(int)) ;

If you need to grow the stack you allocate a new array like this :

 temp= (char*) malloc(sizeof(char)* (*sz+2) );

So you allocate the whole array at one.

But for some reasons , when you are poping an item you do this :

 free(stx->ptArray[stx->top]);

You never allocated this. you allocated ptArray so if you have to free something , it is ptArray.

Just like you did in your grow function :

  free(*array);

I hope your error is clear now.This is what is causing the segmentation fault. However you still have some issues with the management of your stack.

Comments