C: 如何检查用户 NULL 输入

标签 c null user-input

我正在构建一个可遍历的目录树。

这是我的“cd”shell 命令代码。

cd directoryName - 返回带有 directoryName 的目录

cd - 返回根目录

cd .. - 返回当前目录的父目录

如何检查返回根目录的 NULL 用户输入?

if (strcmp(arg, "") == 0) {
    return root;
}

当您按“cd”时似乎会抛出段错误!

// *checks whether cwd has a subdirectory named arg
// *if yes, the function returns the corresponding tree node (and become new working directory)
// *if no, prints an error message
// *handle cd and cd ..
struct tree_node *do_cd(struct tree_node *cwd, struct tree_node *root, char *arg) {

    // initialising subDir to cwd's first child
    struct list_node *subDir = cwd -> first_child;

    // initialising parDir to cwd's parent
    struct tree_node *parDir = cwd -> parent;

    if (parDir != NULL) {
        if (strcmp(arg, "..") == 0) {
            cwd = parDir;
            printf("Returning to parent directory.\n");
            return cwd;
        }
    }

    if (strcmp(arg, ".") == 0) {
        return cwd;
    }

    if (strcmp(arg, "") == 0) {
        return root;
    }

    // checks if cwd has a subdirectory named arg
    while (subDir != NULL) {
        if (strcmp(subDir -> tree -> string_buffer, arg) == 0) {
            printf("Subdirectory exists: Entering!\n");
            cwd = subDir-> tree;
            printf("Making subdirectory current working directory: name = %s\n", arg);
            printf("Returning current working directory: %s.\n", arg);
            return cwd;
        }
        //else if (strcmp(arg, "") == 0) {
        //    printf("Returning to root directory.\n");
        //    return root;
        //}
        subDir = subDir-> next;
    }

    printf("Directory does not exist!\n");
    return cwd;
}

最佳答案

我的猜测是您的 do_cd 函数被调用时带有 NULL arg 参数,因此是 SIGSEGV。对此进行检查应该可以解决问题:

if (arg == NULL || !strcmp(arg, ""))
   return root;

我不知道你的解析器的实现,但我可以猜测它(可能)永远不会用空字符串(“”)调用你的do_cd函数精氨酸。

关于C: 如何检查用户 NULL 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35258364/

相关文章:

c - 将命令行参数读入 c 中的新数组?

c - 在甚至不编辑它的函数调用后取随机值的整数

scala - 在分配 "null"之前,必须限制类型是什么?

c - 在 for 循环中使用 strtok

.net - 当编译器坚持认为不可能时,如何从 Newtonsoft 检查 `null`?

ios - 如果字符串中存在意外字符,NSNumberFormatter 返回 nil

python - 将用户输入用于 Python 的正则表达式是否安全?

java - 搜索和显示结果[java]

python - 如何在 Python 中使用用户输入打印列表的特定部分

c - 为什么 makefile 坚持编译它不应该编译的东西?