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命令的功能?