whatthekey
whatthekey

Reputation: 23

Pointer being freed was not allocated! Cannot be solved

I wrote a function to run linux command (still modifying).

Why free(path) at the last makes error?

Here is code:

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: *** error for object 0x7fff5fbffe21: pointer being freed was not allocated

and am i right on writing command function of linux?

Upvotes: 0

Views: 284

Answers (1)

kaylum
kaylum

Reputation: 14044

Every time you call strtok you are changing the value of path. That doesn't work as free requires the original pointer. Just save a copy of path first and use that for the strtok or free.

Upvotes: 3

Related Questions