0

I'm actually facing some weird issue while coding for university project.

I've implemented a stack struct, and trying to make basic functions to manipulate it.

typedef struct _stack {
    unsigned int max_capacity;
    int* array;
    int top_position;
} stack;

int isFull(stack* s){
    return s->top_position >= (s->max_capacity - 1);
}

int isEmpty(stack* s){
    return s->top_position == -1;
}

void push(stack* s, int elt){
    if (isFull(s)) return;
    s->array[++s->top_position] = elt;
}

int pop(stack* s){
    return s->array[s->top_position--];
}

int peek(stack* s){
    return s->array[s->top_position];
}

stack* createStack(unsigned int capacity){
    stack* s = malloc(sizeof(stack));
    s->max_capacity = capacity;
    s->array = malloc(sizeof(int) * capacity);
    s->top_position = -1;
    return s;
}

But when I try to test it, I got akward results :

stack* s = createStack(5);
if(isFull(s)) printf("Stack full.\n");
printf("Stack top position : %d, stack capacity : %d\n", s->top_position, s->max_capacity);
printf("-1 >= 4 : %d\n", -1 >= 4);
printf("top position >= (capacity - 1) : %d\n", s->top_position >= (s->max_capacity - 1));

returning

Stack full.
Stack top position : -1, stack capacity : 5
-1 >= 4 : 0
top position >= (capacity - 1) : 1

I don't understand the reason why my function isFull is returning a non-zero value when instantiating a new stack.

I put a strict-equality condition instead of greater-or-equal, and now it's working fine, but I need to understand the deep reason of my mistake, can you help me and explain me why the first version wasn't working ?

Thanks.

EDIT: This question is not really a duplicate of the answer linked in comment. Actually I didn't figured that I was comparing signed and unsigned values.

valkorai
  • 40
  • 6

2 Answers2

0

It's because you're comparing an unsigned value with a signed value. During this, your signed value is promoted to an unsigned, and -1 when converted to an unsigned is much much bigger than your max capacity variable.

Be careful when mixing types. To fix this, you could either make your max_capacity a signed value, or explicitly cast it to signed int before making a comparison.

StereoBucket
  • 423
  • 3
  • 9
0

It can be confusing to compare an int and an unsigned int.

In this case, to do the comparison the (signed) top_position value is cast to an unsigned. The -1 ends up as 0xFF..FF and the comparison is done against that.

Best practice: use int or use unsigned int, don’t mix them.

Bob Jacobsen
  • 1,150
  • 6
  • 9