简体   繁体   中英

What is this strange error in my c program?

Below is a code for checking correct parentheses. I couldn't figure out what is causing this strange error.

In int main() whenever I enter a eq[] with size < 6 my code doesn't work unless I enter an extra 3rd line of code I don't know why but it works fine.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Stack
{
    int size;
    int top;
    char * arr; 
};

int isEmpty(struct Stack * ptr)
{
    if(ptr-> top < 0)
    {
        return 1;
    }
    
    return 0;
}

void push(struct Stack * ptr)
{
    ptr->top ++;
    ptr->arr[ptr->top] = '(';
}

void pop(struct Stack * ptr)
{
    ptr->top += -1;
}

int parentheses_checker(int size, char eq[])
{   
    struct Stack *s;
    s->size = size;
    s->top = -1;
    s->arr = (char *) malloc (s->size * sizeof(char));

    int i = 0;
    while(eq[i] != '\0')
    {   
        if (eq[i] == '(')
        {
            push(s);
        }

        else if (eq[i] == ')')
        {
            if(isEmpty(s))
            {
                return 0;
            }

            pop(s);
        }

        i++;
    }

    if(isEmpty(s))
    {
        return 1; // Correct parenthese
    }

    return 0;
}

int main()
{   
    char eq[] = "(("; // Why it is not working for any string wth size 7 or less ??????????
    int size = strlen(eq);
    printf("%d\n", size); // Why is this this happening that if I remove this statement my code stops working ??????
    int result = paranthesis_checker(size, eq);

    if(result == 1)
    {
        printf("Paranthesis are correct\n");
    }
    else if(result == 0)
    {
        printf("Incorrect paranthesis\n");
    }

    return 0;

}

This is wrong:

struct Stack *s;
s->size = size;

The first line defines s to be a pointer. It does not initialize it to anything. Its value is indeterminate .

Then s->size attempts to use the value of the pointer to access something it points to. Since s has not been set to point at anything, this is wrong.

You must set s to point to something before you use it. It may be you do not want a pointer here; you may want a single structure, struct Stack s; , rather than a pointer to a structure. After making that change, you would need to change s-> to s. in several places and s in the function calls to &s .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM