2016-03-08 119 views
0

我写了一个函数来运行linux命令(仍在修改)。被释放的指针未被分配!无法解决

为什么自由(路径)在最后造成错误?

这里是代码:

void cmd_other(char *cmd){ 
    char *env; 
    env = getenv("PATH"); 
    char * path = malloc(424); 
    path = strtok(env, ":"); 
    int notExist = 1; 

    while(path != NULL){    //this will break all $PATH variables by":" 
    char *file = malloc(424); 
    strcat(file, path); 
    strcat(file,"/"); 
    strcat(file, cmd); 
    printf("%s\n", path); 
    if(access(file, X_OK) == 0){ 
     pid_t child_pid; 
     pid_t pid = fork(); 
     int child_status = 0; 
     if(pid == 0){     //since execvp() will end the process 
     char *args[] = {file, (char *) NULL}; 
     execvp(file,args); 
     exit(0); 
     } 
     else{ 
     child_pid = wait(&child_status); 
     notExist = 0; 
     break; 
     } 
    } 
    path = strtok(NULL, ":"); 
    free(file); 
    } 
    if(notExist){   // if the command not exist in $PATH 
    printf("%s: command not found\n", cmd); 
    } 
    free(path); 
} 

的malloc:***错误对象0x7fff5fbffe21:被释放的指针没有被分配

和我说的对编写的Linux命令的功能?

回答

3

每次拨打strtok即表示您更改path的值。这不起作用free需要原始指针。请首先保存一份path,然后将其用于strtokfree

相关问题