繁体   English   中英

fgets() 和初始化变量的奇怪程序行为

[英]Odd program behavior with fgets() and initialized variables

请考虑以下程序代码

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

int main(void)
{
    char *cmd;
    int exitCommand = 1;
    int validCommands = 0;
    int commandValid = 0;

    while(exitCommand != 0)
    {
        printf("> ");
        fgets(cmd, 101, stdin);
        if(*cmd != '\n')
        {
            printf("%s\n", cmd);
        }
        exitCommand = strncmp("exit", cmd, 4);
    }
    return 0;
}

I am compiling this program in Windows 10 x64 cmd via gcc -o cmmd cmmd.c and then running via cmmd The program seems to terminate unexpectedly without printing the output. 但是,如果我删除了除exitCommand之外的至少一个变量,或者不初始化除exitCommand之外的变量,则程序运行正常。 我很困惑是什么导致了这个问题。 堆栈 memory 应该不是问题,因为所有这些占用不到 1000000B。 我怀疑fgets()可能会导致这种情况,但没有可以参考的运行时错误。 我是否应该为cmd字符数组分配显式空间? 使用的编译器是TDM-GCC 请解释现象。

char* cmd未初始化。 为了能够存储输入,您必须使cmd指向有效数组的地址:

char cmd[100];
fgets(cmd, 100, stdin);
// here you can use cmd as a null terminated string

您还应该检查fgets返回值以检测任何错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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