cinhori
cinhori

Reputation: 11

How to debug this C code for a stack implementation?

I am new at C programming. I wrote some code for a stack exercise. The question is: one of the result is wrong, but when I debug step by step, the number changed abruptly. Could you help me solve this?

// @name mystack.c
// Created by lilei on 2017/3/10.
//
#include "mystack.h"
#include <malloc.h>
#include <stdio.h>

Stack createStack(){
    Stack stack = (Stack)malloc(sizeof(Stack));
    stack->top = -1;
    return stack;
}

int isFull(Stack s){
    if (s->top == MAXSIZE-1){
        return 1;
    } else{
        return 0;
    }
}

int push(Stack s, ElementType item){
    if(!isFull(s)){
        s->top++;
        s->data[s->top] = item;
        return 1;
    } else{
        printf("full!");
        return 0;
    }
}


int isEmpty (Stack s){
    if(s->top == -1){
        return 1;
    } else{
    return 0;
    }
}

ElementType pop(Stack s){
if(!isEmpty(s)){
    ElementType e = s->data[s->top];
    s->top--;
    return e;
}
}

void myPrintf(Stack s){
    int len = s->top;
     printf("The data are ");
   while(len >= 0){
        printf("%d ", s->data[len]);
        len--;
    }
    printf("\n");
}

int main(){
    Stack s = createStack();
    for(int i = 0; i < 7; i++){
        push(s, i*2);
    }
    myPrintf(s);

    printf("isEmpty:%d, isFull:%d\n, pop one:%d", isEmpty(s), isFull(s), pop(s));
}

The result is

enter image description here

Upvotes: 1

Views: 82

Answers (1)

JeremyP
JeremyP

Reputation: 86651

I can't see the declaration of Stack because you forgot to put it in th question, but it must be declared as a pointer to a struct e.g.

typedef struct
{
    int top;
    ElementType data[MAXSIZE];
}  *Stack;
// ^- means pointer

So a Stack is a pointer type which means that, when you malloc it, you malloc only 4 or 8 bytes depending on whether you are compiling for 32 or 64 bit. The malloc line should be

Stack stack = malloc(sizeof *stack);

You were not allocating enough space on your stack for the actual stack structure which means that you are writing into bits of the heap you do not own and other things will write into the memory you think you have allocated for your stack.

There is another problem. What does your pop() function return if you try to pop something when the stack is empty? The answer is "could be anything". You either need to abort the program or return some error value.

Upvotes: 2

Related Questions