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