正在释放的指针未分配!无法解决

Pointer being freed was not allocated! Cannot be solved

我写了一个函数给运行linux命令(还在修改中)。

为什么free(path)最后出错了?

代码如下:

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 正确吗?

每次调用 strtok 时,您都在更改 path 的值。这不起作用,因为 free 需要原始指针。只需先保存 path 的副本,然后将其用于 strtokfree