开发者

execv and testing correct absolute paths

开发者 https://www.devze.com 2023-04-07 14:16 出处:网络
I\'m trying to test absolute paths on a l开发者_StackOverflow中文版inux machine to find where a program is located so I can run it with my specific arguments. The problem is, when I find it, I keep ad

I'm trying to test absolute paths on a l开发者_StackOverflow中文版inux machine to find where a program is located so I can run it with my specific arguments. The problem is, when I find it, I keep adding more strings to the correct path as well as memory leak by freeing the dynamically allocated memory. Only fix for the stack dump is to not free(ret). I believe based on gdb that when I run an example with "ls" it finds the program and runs it, but gives strange results.

  for(j = 0; j < i; j++, path = NULL)
  {
  token = strtok_r(path, delim, &saver);
  if(token == NULL)
    break;
  else
    {
      strncat(ret, token, 80);
      strncat(ret, "/", 1);
      strncat(ret, command, 80);
      args[0] = ret;
      printf("%s\n", ret);
      m = execv(ret, args);
      printf("%d\n", m);
      if(m < 0)
        {
          free(ret);
          ret = malloc(120*sizeof(char));
        }
      else
      break;
    }
}

Where the delimiter character is a colon (:) and I believe the strncat is done correctly. I'm not sure though so thanks for the help.


Each time you malloc(), you get new uninitialised memory. strncat() will then raise a segmentation fault as it will try to find a NUL character in ret, which could be way outside of your 120 bytes for ret.

Either replace malloc with calloc, or use memset(ret, 0, 120*sizeof(char)); after you call malloc. Or somehow fill ret with zeros before the first strncat.

The reason it's not breaking if you don't free could be due to ret being declared on the stack - then do not free/malloc it. Or it could so happen that the initial value of ret is all zeros - but subsequent malloc calls yield uninitialised memory.

PS: Are you sure you want to use execv? That replaces the current process. But I assume you fork.

0

精彩评论

暂无评论...
验证码 换一张
取 消