C: 如何检查用户 NULL 输入

C: how to check for user NULL input

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

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

cd directoryName - returns directoryName

的目录

cd - returns根目录

cd .. - returns当前目录的父目录

如何检查返回根目录的 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;

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