C 中的 Minishell 'segmentation fault, core dumped' 错误
Minishell 'segmentation fault, core dumped' error in C
以下是我的 shell 代码的一部分。该代码有效,但是当我尝试输入“ls”之类的命令时,我的程序崩溃了。我认为这是一个正确的错误,因为我试图访问“/bin”文件。
void lecture (char cmd1[], char *argv[]){
int x = 0;
char ligne [1024];
char *aux [100], *pch;
while (1){
int mot = fgetc (stdin);
ligne[x] = (char) mot;
x++;
if (mot == (int)'\n') break;
}
aux[0] = strtok (ligne, " \n");
strcpy(cmd1,aux[0]);
for (int i = 1; i <= 1024; i++){
argv[i+1] = aux[i];
}
}
int main(){
char cmd1 [100];
char cmd2 [100];
int a = 10;
char *argv [20];
char *envp[] = {(char *) "PATH=/bin", 0};
while (1){
affichage();
lecture (cmd2, argv);
printf("Test");
if ( fork() != 0){
printf("Err");
wait (NULL);
}else{
strcpy(cmd1, "/bin/");
strcat(cmd1, cmd2);
execve(cmd1, argv, envp);
}
}
}
在 lecture
中进行以下修改后,我在没有 SIGSEGV 的情况下得到了一些东西:
for (int i = 0; i < 20; i++){
示例:
./ms
ls
����: cannot access 'ls': No such file or directory
TestErr
...
但是你也可以像我在调试模式下编译一样调试它:
gcc -o ms -g -Wall -pedantic -Wextra -std=c11 ms.c
并使用 gdb
检查 SIGSEGV 发生的位置。
请注意,您需要 post 具有完整代码的 https://whosebug.com/help/minimal-reproducible-example(这里我们缺少 affichage
)和
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
以下是我的 shell 代码的一部分。该代码有效,但是当我尝试输入“ls”之类的命令时,我的程序崩溃了。我认为这是一个正确的错误,因为我试图访问“/bin”文件。
void lecture (char cmd1[], char *argv[]){
int x = 0;
char ligne [1024];
char *aux [100], *pch;
while (1){
int mot = fgetc (stdin);
ligne[x] = (char) mot;
x++;
if (mot == (int)'\n') break;
}
aux[0] = strtok (ligne, " \n");
strcpy(cmd1,aux[0]);
for (int i = 1; i <= 1024; i++){
argv[i+1] = aux[i];
}
}
int main(){
char cmd1 [100];
char cmd2 [100];
int a = 10;
char *argv [20];
char *envp[] = {(char *) "PATH=/bin", 0};
while (1){
affichage();
lecture (cmd2, argv);
printf("Test");
if ( fork() != 0){
printf("Err");
wait (NULL);
}else{
strcpy(cmd1, "/bin/");
strcat(cmd1, cmd2);
execve(cmd1, argv, envp);
}
}
}
在 lecture
中进行以下修改后,我在没有 SIGSEGV 的情况下得到了一些东西:
for (int i = 0; i < 20; i++){
示例:
./ms
ls
����: cannot access 'ls': No such file or directory
TestErr
...
但是你也可以像我在调试模式下编译一样调试它:
gcc -o ms -g -Wall -pedantic -Wextra -std=c11 ms.c
并使用 gdb
检查 SIGSEGV 发生的位置。
请注意,您需要 post 具有完整代码的 https://whosebug.com/help/minimal-reproducible-example(这里我们缺少 affichage
)和
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>