叼着指针......在书中?

时间:2012-07-21 19:28:47

标签: c

我可能错过了一些东西但只想问...我在高级Linux编程一书中找到了这段代码:

    char* get_self_executable_directory ()
    {
      int rval;
      char link_target[1024];
      char* last_slash;
      size_t result_length;
      char* result;
      /* Read the target of the symbolic link /proc/self/exe. */
      rval = readlink (“/proc/self/exe”, link_target, sizeof (link_target));
      if (rval == -1)
        /* The call to readlink failed, so bail. */
        abort ();
      else
        /* NUL-terminate the target. */
        link_target[rval] = ‘\0’;
      /* We want to trim the name of the executable file, to obtain the
      directory that contains it. Find the rightmost slash. */
      last_slash = strrchr (link_target, ‘/’);
      if (last_slash == NULL || last_slash == link_target)
        /* Something strange is going on. */
        abort ();
      /* Allocate a buffer to hold the resulting path. */
      result_length = last_slash - link_target;
      result = (char*) xmalloc (result_length + 1);
      /* Copy the result. */
      strncpy (result, link_target, result_length);
      result[result_length] = ‘\0’;
      return result;
    }

我的问题是,这个函数不会返回一个悬空指针吗?

2 个答案:

答案 0 :(得分:8)

它返回一个指针,并期望在客户端代码中完成释放。当你看到返回指针的函数时,你总是要问自己(实际上是作者......)内存的所有权(这是解除它的责任)是否传递给函数的客户端,如果是这样,它究竟应该如何被释放。

答案 1 :(得分:5)

不 - 它分配内存,然后返回。