C语言中括号平衡

parentheses balanced in C language

这是括号平衡的代码。我提交并得到了教授的评论。

"Your stack is supposed to grow and shrink dynamically to accommodate any number of characters. DO NOT USE scanf for %s, this is risky behavior and Dr. Adams does not approve. Write a helper function to read in characters until newline."

你能帮我解决这个问题吗?

你的教授是正确的,他给了你解决方案:不要用 scanf("%s",...) 将一行读入缓冲区:任意长行将导致缓冲区溢出。您不需要阅读整行,只需 check_balanced 一次阅读一个字符:

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

#define TRUE  1
#define FALSE 0

int check_matching(void);

int main(int argc, char *argv[]) {
    int n, i, c;
    /* get the number of cases */
    if (scanf("%d", &n) != 1) {
        printf("invalid number\n");
        exit(1);
    }
    /* consume the rest of the line */
    while ((c = getchar()) != EOF && c != '\n')
        continue;

    for (i = 0; i < n; i++) {
        if (check_matching()) {
            printf("yes\n");
        } else {
            printf("no\n");
        }
    }
    return 0;
}

int check_matching(void) {
    int ret = TRUE, symbol, checkSymbol;
    LinkedStack *pStack;
    StackNode *pNode;
    StackNode node;

    pStack = createLinkedStack();
    if (pStack == NULL) {
        printf("createLinkedStack failed\n");
        exit(1);
    }

    /* read a full line, one byte at a time */
    while ((symbol = getchar()) != EOF && symbol != '\n') {
        if (ret == FALSE)
            continue;
        switch (symbol) {
        case '(':
        case '[':
        case '{':
            node.data = symbol;
            pushLS(pStack, node);
            break;

        case ')':
        case ']':
        case '}':
            pNode = popLS(pStack);
            if (pNode == NULL) {
                ret = FALSE;
                break;
            } else {
                checkSymbol = pNode->data;

                if ((symbol == ')' && checkSymbol == '(')
                ||  (symbol == ']' && checkSymbol == '[')
                ||  (symbol == '}' && checkSymbol == '{')) {
                    // Right case. do nothing.
                } else {
                    ret = FALSE;
                }
                free(pNode);
            }
            break;
        }
    }

    if (isLinkedStackEmpty(pStack) == FALSE) {
        ret = FALSE;
    }
    deleteLinkedStack(pStack);
    return ret;
}