发布
社区首页 >问答首页 >我找不到分段错误的原因

我找不到分段错误的原因
EN

Stack Overflow用户
提问于 2020-12-20 21:24:46
回答 1查看 54关注 0票数 0

我正在尝试用C语言为Linux创建一个基本的类似shell的程序,但我遇到了一些问题。我在我创建的parse_cmdline函数中的某个地方遇到了分段错误,但我预计参数= parse_cmdline (cmdline);可能不是实现我想要做的事情的最佳方法。

代码语言:javascript
代码运行次数:0
复制
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>

char** parse_cmdline(const char *cmdline){

    char** input;
    int counter = 0;
    char* token;
    token = strtok(cmdline);
    
    int tokenlen = strlen(token);
    
    input = realloc(input , sizeof(char*)+tokenlen*sizeof(char));
    input[counter] = token;
        
    while( token != NULL ) {
            token = strtok(NULL, " ");
            printf("%s\n",token);
            tokenlen = strlen(token);
            input = realloc(input , sizeof(char*)+tokenlen*sizeof(char));
            counter++;
            input[counter] = token;
    }
    return input;
}

int main(){

    char* cmdline = NULL;
    size_t cmdlength = 0 ;
    char** arguments;

    int status;
    pid_t pid;
    while (1){
    
        getline(&cmdline , &cmdlength , stdin);
        arguments = parse_cmdline(cmdline);

        pid = fork();
        if(pid == 0){
        
            if(access(arguments[0], F_OK) == 0 ) {
            
                    if(access(arguments[0], X_OK)){
                    
                        execv(arguments[0],arguments);
                        exit(0);
                        
                    } else {
                    
                        printf("%s: Permission denied",arguments[0]);
                        exit(-1);
                    
                    }
                    
            } else {
            
                printf("%s: No such file or directory",arguments[0]);
                exit(-1);
            
            }
            
        } else {
        
            waitpid(-1, &status, 0);
            
        }
            
        free(arguments);
        cmdline = NULL ;
        cmdlength = 0 ;
    }   
    return 0;
}
EN

回答 1

Stack Overflow用户

发布于 2020-12-20 21:43:58

有两个问题立即跳到我的脑海中:

  1. 正如@Bob__在评论中所观察到的,strtok()是破坏性的,所以不应该将const char *作为它的第一个参数。你的编译器至少应该对此进行警告。不要忽视编译器的警告,特别是在你寻找bug的时候。如果您对parse_cmdline()修改字符串没有意见,那么就从它的参数中删除const (而且不要将const数据传递给函数)。如果不希望修改输入数据,则创建本地非const副本或使用strtok().

以外的其他内容

当没有更多的令牌时,

  1. strtok()返回NULL,但是您在没有对其进行测试的情况下使用了它的结果。无论是对于初始strtok()调用还是对于循环中的调用,while条件中的null检查都为时已晚。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65380369

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档