0

我正在尝试在 linux 机器上测试绝对路径以查找程序所在的位置,以便我可以使用我的特定参数运行它。问题是,当我找到它时,我会通过释放动态分配的内存来不断地将更多字符串添加到正确的路径以及内存泄漏。对堆栈转储的唯一修复是不释放(ret)。我相信基于 gdb,当我使用“ls”运行示例时,它会找到程序并运行它,但会给出奇怪的结果。

  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;
    }
}

分隔符是冒号 (:) 的地方,我相信 strncat 是正确完成的。我不确定,但感谢您的帮助。

4

1 回答 1

0

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.

于 2011-09-27T01:35:27.170 回答