c - Pop 在特定函数中仅起作用一次

标签 c memory-management stack singly-linked-list c-strings

我将堆栈实现为链表,我想制作一个函数来告诉括号是否顺序良好,例如: (()) 是好的 ())( 是坏的。函数的逻辑现在不好,但我不知道为什么 pop() 只工作一次。这是我的代码(stog 是堆栈,sljedeci 是下一个):

struct stog {
    int x;
    stog *sljedeci;
};

typedef struct stog stog;

stog *top;
char pop() {
    stog *temp;
    temp = (stog*)malloc(sizeof(stog));
    temp = top;
    char n = temp->x;
    top = temp->sljedeci;
    top->x = temp->sljedeci->x;
    free(temp);
    return n;
}



void init() {
    top = NULL;
}

void push(char x) {
        stog *temp;
        temp=(stog*)malloc(sizeof(stog));
        temp->x = x;
        temp->sljedeci = top;
        top = temp;
    }

 void Brackets(const char* msg) {
    char z;
    for (int i = 0; i < strlen(msg); i++) {
        if (msg[i] == '(') {
            push('(');
        }
        if (msg[i]==')'){
            z = pop();
            printf("Bad\n");    
        }       
    }
}

int main() {

    const char* msg = "(())";
    init(); 
    Brackets(msg);
    return 0;
}

输出为:

不好

应该是:

不好 不好

编辑:添加了 init() 和 push() 函数

最佳答案

pop 中的这一行没有意义:

top->x = temp->sljedeci->x;

在上一行中,您将 temp->sljedeci 分配给 top。所以这里引用的 x 成员实际上两边都是同一个,所以假设 top 和 temp->sljedeci 都不为 null没有什么。如果其中一个为 NULL,则调用 undefined behavior因为您取消引用空指针。所以去掉这条线。

您在 pop 中也存在内存泄漏:

temp = (stog*)malloc(sizeof(stog));
temp = top;

您分配内存并将其地址分配给 temp,但随后立即用 top 的值覆盖该地址。

此处无需分配更多内存,因此请删除 malloc 调用。

关于c - Pop 在特定函数中仅起作用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59886477/

相关文章:

c - 在文本文件中一次读取多行 - C

java - Java 中的 C 格式说明符 "%n"

c++ - 对使用多个内存池的类使用工厂是否合适?有更好的模式/技术吗?

c - C 中的递归堆栈

c - 隐式声明静态的问题(编译自定义的 mupdf 库)

c++ - 用 C/C++ 编译一个 DLL,然后从另一个程序调用它

c - 使用释放的内存有风险吗

java - 如何在 JVM run 调用之间保留大型 Java 对象

python - 了解栈帧在递归函数中的工作原理

在 R 中 reshape 数据