c - 解决 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 更改为指针,它只是给了我更多错误我该怎么办?
解决方案
您的代码片段中有许多未声明的变量。您还需要获取主机名,它不是全局变量。在使用函数之前声明函数也是一种最佳实践。
这工作正常:
#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;
}
推荐阅读
- javascript - 使用 Angular 5 中的服务在两个不相关的组件之间共享数据
- c++11 - 用 && 声明局部值是否有任何值得优化的地方
- java - 有没有办法从 Java 类创建 POJO?
- java - 具有 java 不可修改列表实现和 createAndAdd 之类的方法的库?
- admin-on-rest - react-admin 中的树结构
- javascript - 健全性检查:`util.inherits(Child, Parent);`:附加到 Child 的原型属性的东西不应该影响 Parent 的属性?
- angular - angular 4 形式中至少需要一个字段
- c++ - 使用 wcstod 转换零值
- shell - xmlstarlet 替换模式后的值
- javascript - 如何在 JavaScript 中不可变地打乱数组?