代码之家  ›  专栏  ›  技术社区  ›  Ritwik Bose

在C中:为什么堆栈分配结构存在于函数之外?

  •  5
  • Ritwik Bose  · 技术社区  · 16 年前

    struct hostent * gethost(char * hostname){
        if(/*some condition under which I want 
             to change the mode of my program to not take a host*/){
           return null
        }
        else{
            struct hostent * host = gethostbyname(hostname);
            return host;
        }
    }
    

    大体上:

    struct hostent * host = gethost(argv[2]);
    

    为什么?我以为堆栈上分配的东西会随着函数调用的返回而消失?还是因为我返回了指针?这有什么危险吗?

    4 回复  |  直到 16 年前
        1
  •  10
  •   Gabe Timothy Khouri    16 年前

    host

    注意 gethostbyname hostent 如果要保存值以备以后使用,则函数将返回,因为以后会调用 gethost 将覆盖它。

        2
  •  3
  •   kennytm    16 年前

    这很好,而且确实会泄漏,因为返回的指针不指向堆栈或堆上的数据,而是指向某个静态变量。

    http://linux.die.net/man/3/gethostbyname

    . 复制结构宿主是不够的,因为它包含指针;需要一份深度副本。

        3
  •  2
  •   Ben    16 年前

    从手册中:

    RETURN VALUE
           The gethostbyname() and gethostbyaddr() functions  return  the  hostent
           structure  or a NULL pointer if an error occurs.  On error, the h_errno
           variable holds an error number.  When non-NULL, the  return  value  may
           point at static data, ...
    

    在编译时为结构保留了一些内存(即在二进制代码中),函数返回指向该内存的指针。

        4
  •  0
  •   monoceres    16 年前

    在所有对它的引用丢失之前,内存不会泄漏,在您的示例中,指针被返回,因此仍然存在对它的引用。