【问题标题】:Why is my program printing this C-String? [duplicate]为什么我的程序要打印这个 C 字符串? [复制]
【发布时间】:2020-10-07 00:06:33
【问题描述】:

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

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() 函数会打印这个?

谢谢!

【问题讨论】:

  • 如果没有匹配项会怎样?你退回垃圾。您可能正在尝试比较 "help\n" 并且它无法匹配,返回一个未初始化的指针。
  • fgets 包含一个尾随换行符
  • 提示:尽量不要使用显微缓冲液。而是使用 1024 作为默认值,并根据需要从那里上升。 10 个字节绝对是荒谬的,当您使用中等长度的命令名称或稍后添加参数时,10 个字节会为您自己设置溢出错误,例如 "list names" 太长,即 10 个字符,并且您的缓冲区只能容纳 9 + NUL 终止符。跨度>
  • @tadman 这正是问题所在。谢谢!

标签: c shell c-strings


【解决方案1】:

这里有两个问题:

  • fgets 记录为“如果找到换行符...str 将包含该换行符”,因此您实际上将"help\n" 作为输入。您需要删除该换行符或预期它。
  • 当这些都不匹配时,您的if 链无法解决这种情况。您应该有一个默认的 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 表达。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    相关资源
    最近更新 更多