首页 > 解决方案 > 解决 C 中的越界问题,使用 ls 命令时的问题

问题描述

我正在尝试在 C 中制作一些什么 shell,但我在制作ls命令时遇到了问题。 mkdir,并且cd工作正常,但ls它给了我

“地址越界分割错误”

希望有人能帮助我。这是我的代码。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <readline/readline.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    printf("\033[1;33mWelcome To Crisp Bacon Shell\n");
    while (1) {
        printf("\033[0m%s $", hostname);
        input = readline("");
        command = get_input(input);

        child_pid = fork();
         if (child_pid < 0) {
            perror("Fork failed");
            exit(1);
        }else if (child_pid == 0) {
            /* Never returns if the call is successful */
            execvp(command[0], command);
            printf("This won't be printed if execvp is successul\n");
        } else {
            waitpid(child_pid, &stat_loc, WUNTRACED);
        }

        free(input);
        free(command);
    }
    return 0;
}

char **get_input(char *input) {
    char **command = malloc(8 * sizeof(char *));
    char *separator = " ";
    char *parsed;
    int index = 0;

    parsed = strtok(input, separator);
    while (parsed != NULL) {
        command[index] = parsed;
        index++;

        parsed = strtok(NULL, separator);
    }

    command[index] = NULL;
    return command;
}

我唯一了解它与内存和引用或指针有关,但我尝试将所有内容从 & refrencing 更改为指针,它只是给了我更多错误我该怎么办?

标签: cunixterminal

解决方案


您的代码片段中有许多未声明的变量。您还需要获取主机名,它不是全局变量。在使用函数之前声明函数也是一种最佳实践。

这工作正常:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <readline/readline.h>
#include <unistd.h>
#include <sys/wait.h>

char **get_input(char *input) {
    char **command = malloc(8 * sizeof(char *));
    char *separator = " ";
    int index = 0;

    char *parsed = strtok(input, separator);
    while (parsed != NULL && index < 8) { // you need to make sure the index does not overflow the array
        command[index] = parsed;
        index++;

        parsed = strtok(NULL, separator);
    }

    command[index] = NULL;
    return command;
}

int main() {
    printf("\033[1;33mWelcome To Crisp Bacon Shell\n");
    while (1) {
        // hostname does not exist, you need to fetch it
        char hostname[1024];
        gethostname(hostname, 1023); // POSIX only
        printf("\033[0m%s $", hostname);
        char *input = readline(NULL);
        char **command = get_input(input);

        pid_t child_pid = fork();
        if (child_pid < 0) {
            perror("Fork failed");
            exit(1);
        } else if (child_pid == 0) {
            /* Never returns if the call is successful */
            execvp(command[0], command);
            printf("This won't be printed if execvp is successul\n");
        } else {
            waitpid(child_pid, NULL, WUNTRACED); // since you don't use the middle argument, no need to point to valid data
        }

        free(input);
        free(command);
    }
    return 0;
}

推荐阅读