为什么我的程序打印这个 C 字符串?

Why is my program printing this C-String?

我目前正在为我的操作系统开发一个项目 class 并且发现了一个奇怪的错误,在打印处理用户在命令行中输入的文本时生成的字符串时。这是程序的输出:

JR > help
H�E�����UH��SH��(H�}��E�

这里是产生这个输出的副本:

/*
* File: hw3.c
* Purpose: To demonstrate a shell by allowing a user to enter commands 
* and perform actions depending on the command.
*/

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

/* Function Prototypes */
void printPrompt();
char* parseCommand(char* cmd);
char* readCommandLine();

/*
 * Entry point of the program.
 */
int main(int argc, char **argv) {
    while(1) {
        printPrompt();

        char* cmdLine = readCommandLine();
        char* cmd = parseCommand(cmdLine);

        printf("Selected Command: %s", cmd);
    }
}

/*
 * This function prints a prompt to the user to enter a command.
 */
void printPrompt() {
    printf("\n%s", "JR > ");
}

/**
 * This function reads the command the user enters from the terminal.
 */
char* readCommandLine() {
    char* input = malloc(10);
    
    fgets(input, 10, stdin);

    return input;
}

char* parseCommand(char* cmd) { 
    char *selectedCommand; /* The command to return */

    /* Convert cmd to all lowercase and store it in enteredCommand. */
    int i;
    for (i = 0; i < strlen(cmd); i++)
        cmd[i] = tolower(cmd[i]);

    if (strcmp(cmd, "cd") == 0)
        selectedCommand = "cd";
    else if(strcmp(cmd, "help") == 0)
        selectedCommand = "help";
    else if(strcmp(cmd, "pwd") == 0)
        selectedCommand = "pwd";
    else if (strcmp(cmd, "exit") == 0)
        selectedCommand = "exit";

    return selectedCommand;
}

谁能解释为什么 printf() 函数打印这个?

谢谢!

这里有两个问题:

  • fgets 被记录为“如果找到换行符......str 将包含该换行符”所以你实际上得到 "help\n" 作为输入。您需要删除该换行符或预测它。
  • 您的 if 链无法解决 none 匹配的情况。您应该有一个默认的 return NULL 处理程序。

我会重写该块以使其更安全,如下所示:

char* parseCommand(char* cmd) { 
    // Move declaration inside of for()
    for (int i = 0; i < strlen(cmd); i++)
        cmd[i] = tolower(cmd[i]);

    if (strcmp(cmd, "cd") == 0)
        return "cd";
    else if(strcmp(cmd, "help") == 0)
        return "help";
    else if(strcmp(cmd, "pwd") == 0)
        return "pwd";
    else if (strcmp(cmd, "exit") == 0)
        return "exit";

    return NULL;
}

现在它不可能以不一致的状态掉到底部。

从技术上讲,现在这些都可以是简单的 if 语句,else 已经通过 return.

表达了