You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中wordToGuess变量值丢失问题求助

猜词游戏中wordToGuess变量值丢失问题求助

我正在开发一个猜词项目,用户拥有一定次数的尝试机会。问题在于当代码执行到标记为“HERE LOSES ITS VALUE”的位置时,变量wordToGuess会丢失其值。我尝试了多种方法仍无法解决,恳请您的帮助!(checkExistence是一个检查单词是否存在于字典中的函数)

代码片段

void  newGame(node* head){
    char wordToGuess[10];
    char attempt[10];
    int numberOfAttempts = 0;

   if (scanf("%s" , wordToGuess) != 1){
        printf("error1");
    }
    getchar();

    if (scanf("%d", &numberOfAttempts) != 1){
        printf("error2");
    }
    getchar();

    while(numberOfAttempts > 0){
        if (scanf("%s", attempt) != EOF){
            if (attempt[0] != '+'){
                if (checkExistence(head, attempt) == false){
                    printf("not_exists\n");
                }else{
                    if (strcmp(wordToGuess, attempt) == 0){
                        printf("ok\n");
                        return;
                    }else{
                        //code
                        numberOfAttempts--;
                    }
                }
            }else{
                if (attempt[0] == '+' && attempt[1] == 's'){
                    //HERE LOSES ITS VALUE
                }else if (attempt[0] == '+' && attempt[1] == 'i'){
                    //other code
                }
            }
        }else{
            printf("ko");
            return;
        }
    }
    return;
}

测试用例

2rj9R (wordToGuess)
18 (numerAttemps)
DP3wc (attempt)
7PGPU (attempt)
2rz9R (attempt)
+print_list (from this point I lose the value of wordToGuess)
2rj9R (attempt)

问题原因与解决方法

核心原因:栈缓冲区溢出

测试用例中的+print_list字符串长度为11个字符(包含开头的+),而你定义的attempt数组仅分配了10字节空间。C语言中字符串需要额外1字节存储结束符\0,当用scanf("%s", attempt)读取该字符串时,会超出attempt的内存边界,覆盖栈上相邻的变量——wordToGuess正好位于attempt的相邻位置,因此它的值被破坏。

解决步骤

  1. 扩大数组容量
    将char wordToGuess[10];和char attempt[10];修改为更大的数组,比如:

    char wordToGuess[20];
    char attempt[20];
    

    给输入留足够的冗余空间,避免短数组无法容纳长字符串。

  2. 使用安全的输入方式
    避免无限制读取字符串,防止缓冲区溢出:

    • 用带长度限制的scanf:
      scanf("%19s", attempt); // 最多读取19个字符,留1个给'\0'
      
    • 更推荐使用fgets配合字符串处理函数,能更好处理换行符:
      if (fgets(attempt, sizeof(attempt), stdin) != NULL) {
          // 去掉输入末尾的换行符
          attempt[strcspn(attempt, "\n")] = '\0';
      }
      
  3. 优化输入处理逻辑
    当前的getchar()调用存在隐患,若用户输入后有多余字符或多个换行,会导致后续读取异常。改用fgets读取整行输入,再用sscanf解析内容,能提升输入处理的可靠性。

内容的提问来源于stack exchange,提问作者Sebastiano Mora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 07:24:23