In my code there is a code fragment which checks to see if a certain character is contained in a character stack data structure:
Code:
int containsChar(struct CharStack stack, char token){
if(!stack.stackPointer){
fprintf(stderr, "Character Stack is empty, doesn't contain anything \n");
exit(-1);
}
for(int i = 0; i <stack.stackPointer; i++){
if(stack.stackValues[i] == token){
return i;
}
}
return -1;
}
If the stack doesnt contain anything I exit() the programme execution.
What is absolutely baffling to me is that when I try this snippet on an empty stack, I expect the programme to exit with the output "Character Stack is empty, doesn't contain anything".
Instead what it does is print "Number Stack empty" prior to exiting immediately thereafter. The only other place in my code base where this wording is contained is in pop number function:
Code:
double popNum(struct NumStack *stack){
if (stack -> stackPointer > 0){
return stack -> stackValues[--stack -> stackPointer];
}
else {
fprintf(stderr, "Number Stack empty\n");
exit(-1);
}
}
When I debug this programme line by line, the last statement prior to exiting is in the containsChar function and not the popNum function. Infact the latter function is never even stepped into. Its as if the compiler is doing whatever it wants which leads me to suspect that there is undefined behaviour somewhere in here.
Any ideas?