C:如何检查用户NULL输入

时间:2016-02-07 20:00:14

标签: c null user-input

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

这是我的'cd'hell命令的代码。

cd 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;
}

1 个答案:

答案 0 :(得分:2)

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

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

我不知道你的解析器的实现,但我猜可能(可能)永远不会用arg的空字符串(do_cd)调用你的""函数。