在c中使用free()时发生异常,分段错误;

问题描述 投票:0回答:1

我的代码以某种方式运行,但它没有给出预期的结果,所以为了理解它,我开始调试,它显示发生了异常,我使用

free()
的行出现了分段错误。 这是我的代码:

struct stack
{
    char ch;
    struct stack *prev;
} *top = NULL;

typedef struct stack st;

char pop();
void push(char c);
int evaluate(char arr[100]);

int main()
{
    char arr[100];
    printf("Enter the string to check format of string in wcwR");
    gets(arr);
    if (evaluate(arr) == 1)
    {
        printf("Entered string is in correct format");
    }
    else
    {
        printf("Entered string is in wrong format");
    }
}

int evaluate(char arr[100])
{
    int i;
    for (i = 0; arr[i] != 'c' && arr[i] != 'C'; i++)
    {
        push(arr[i]);
    }
    i++;
    int j = i;
    int flag = 0;
    while (arr[j] != '\0')
    {
        if (arr[j] != pop())
        {
            return 0;
        }
        else
        {
            flag = 1;
        }
    }
    if (flag == 1)
    {
        return 1;
    }
}

void push(char c)
{
    st *p;
    p = (struct stack *)malloc(sizeof(struct stack));
    p->ch = c;
    p->prev = top;
    top = p;
}

char pop()
{
    st *temp;
    char item;
    temp = top;
    item = top->ch;
    top = top->prev;
    **free(temp);** //here exception occurred 
    return item;
}

请帮助我解决这个问题,任何人都可以建议任何合适的技术来自己解决这样的问题吗?谢谢你。

c exception data-structures malloc free
1个回答
0
投票

您的异常并未发生在您认为发生的地方。弹出时您不会检查空堆栈,即

top == NULL
。然后你尝试用
NULL
取消引用
top->ch

© www.soinside.com 2019 - 2024. All rights reserved.