I tried writing some code to check if the paranthesis in an expression are balances using the below function. Can someone help me understand why the below function is returning 1 in case of a balanced expression when it's not specified anywhere to return 1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
struct Stack
{
int top;
unsigned capacity;
char* array;
};
struct Stack* createStack (unsigned capacity)
{
struct Stack* stack = (struct Stack*) malloc (sizeof(struct Stack));
if(!stack)
return NULL;
stack->top = -1;
stack->capacity = capacity;
stack->array = (char*) malloc(stack->capacity * sizeof(int));
if (!stack->array)
return NULL;
return stack;
}
int isEmpty(struct Stack* stack)
{
return (stack->top == -1);
}
void push(struct Stack* stack, char op)
{
stack->top++;
stack->array[stack->top] = op;
}
int pop(struct Stack* stack)
{
if (!isEmpty(stack))
return (stack->array[stack->top--]);
return '$';
}
int isMatchingPair(char char1 , char char2)
{
if (char1 == '(' && char2 == ')')
return 1;
else if (char1 == '[' && char2 == ']')
return 1;
else if (char1 == '{' && char2 == '}')
return 1;
else
return 0;
}
int paranthesesMatch(char* exp)
{
int i;
struct Stack* stack = createStack(strlen(exp));
for(i = 0; exp[i]; i++)
{
if (exp[i] == '(' || exp[i] == '[' || exp[i] == '{')
push(stack , exp[i]);
if (exp[i] == ')' || exp[i] == ']' || exp[i] == '}')
{
if (stack == NULL)
return 0;
else if ( !isMatchingPair(pop(stack), exp[i]) )
return 0;
}
}
}
int main()
{
char exp[100] = "{()}[)";
printf(" %d\n", paranthesesMatch(exp));
if (paranthesesMatch(exp) == 1)
printf("Balanced \n");
else
printf("Not Balanced \n");
return 0;
}
Edit: Added the full code.
Your function has branches of code that do not return a value at all. Specifically, when the loop reaches the end, your function does not specify what to return. In situations like that using function's return value is undefined behavior: whatever the function appears to "return" is a junk left-over value that could be different on different computers, or even on the same computer when you run the program multiple times.
As far as the function itself goes, the
NULL
check for a stack is probably incorrect, unless the code deletes thestack
once it's empty (which would be a rather poor decision). In addition, the code has a memory leak, becausestack
is never freed. It also over-allocatesstack->array
content by a factor ofsizeof(int)
(4 on many computers these days):should be
because you make a stack of
char
s, not a stack ofint
s.Finally, there is no need to allocate
stack
dynamically. Allocate an array ofchar
s, and make a "stack pointer" or stack index to point at the beginning of your stack. Increment and decrement the pointer/index when you push/pop elements onto the stack. If you use a variable-length array, you wouldn't need to clean up dynamically allocated memory.