简体   繁体   中英

Odd program behavior with fgets() and initialized variables

Please consider the following program code

#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. However, if I remove at least one of the variables except exitCommand , or don't initialize the variables except for exitCommand , the program behaves properly. I am confused as to what is causing this problem. Stack memory shouldn't be a problem since all this occupies less than 1000000B. I suspect fgets() could be causing this, but there are no run-time errors that I am able to refer to. Should I perhaps have allocated explicit space for cmd char array? The compiler being used is TDM-GCC . Kindly explain the phenomenon.

char* cmd is uninitialized. To be able to store the input, you have to make cmd point to the adress of a valid array:

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

Also you should check for fgets return value to detect any error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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