c - 悬挂指针..在一本书中?

标签 c

我可能遗漏了什么但只是想问一下..我在 Advanced Linux programming 一书中找到了这段代码:

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

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

最佳答案

它返回一个指针并期望释放将在客户端代码中完成。当您看到返回指针的函数时,您总是必须问自己(实际上是作者......)内存的所有权(即释放它的责任)是否传递给函数的客户端,如果是,它应该如何传递获得自由。

关于c - 悬挂指针..在一本书中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11595241/

相关文章:

c - 有谁知道我的 C 程序的这种奇怪输出是如何发生的?

c - 分配int存储?

c - 是否有任何 linux 函数调用可以通过传递线程 ID 来获取特定线程的 CPU 使用率?

c - 从命名管道读取

c++ - GetPath() 是否返回三次或二次贝塞尔曲线控制点?

python - 如何使用 Python 优雅地发送/接收大型 C 结构?

c - 尝试释放时出现堆错误

Python 嵌入 C++ try_rich_compare 类型错误

c - C程序的逐步编译

c - Valgrind 给出错误,但一切似乎都很好