getaddrinfo addrinfo结果在堆栈或堆中 [英] getaddrinfo addrinfo result in stack or heap

查看:92
本文介绍了getaddrinfo addrinfo结果在堆栈或堆中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我至少有点困惑. getaddrinfo()调用更新"指向addrinfo结构的指针,当我要在同一作用域(该函数)中使用addrinfo时,一切都很好,但是如果将结构复制到另一个结构(通过分配结构)会发生什么情况.

I am a bit confused at least. getaddrinfo() call 'updates' a pointer to a addrinfo struct, all is well when I am going to use the addrinfo in the same scope (that function) but what happens if I copy the struct to another one (by assigning it).

请帮助我了解正在进行的基础知识(不要寻求其他方法的建议).

Please help me understand the undergoing basics (not seeking advice for alternative approaches).

如果我错了,请纠正我: a)getaddrinfo()需要一个指向指向addrinfo的结构体指针的指针. b)getaddrinfo在当前函数作用域中创建一个addrinfo结构,并更新a)中所需的指针

Correct me if I am wrong: a) getaddrinfo() requires a pointer to struct-pointer to addrinfo. b) getaddrinfo creates a addrinfo struct in the current function scope and updates the pointer required in a)

现在我真正的问题是:我想将该addrinfo存储在其他地方.使用分配给其他指针不会进行深度复制,并且在该函数之后所有指针都变为无效吗?

Now my real question: i would like to store that addrinfo somewhere else. Using an assigning to an other pointer does not do a deep copy, and after the function all the pointers become invalid?

最好给出一个极为简化的示例:

Better give an extremely simplified example:

void GetAddrInfo(struct addrinfo *update)
{
    struct addrinfo *res;
    getaddrinfo(xx,xx,xx,&res);

    //is this save? After this 'scope' ends all pointed fields are invalid?
    //this doesn't copy the linked list ai_next.
    *update=*res; 
}

直接在getaddrinfo上使用& update似乎不起作用,因为问题仍然存在:在函数作用域结束后,原始结构被破坏了.

Directly using &update on getaddrinfo seems to not work because the problem remains: the original struct get destroyed after the function scope ends.

任何能够在这里给我更多见识的人(请解释欢迎在何处创建,销毁,堆叠,堆放所有信息的内容)

Anyone able to give me more insight here (please explain what gets created where and destroyed where, stack, heap all info is welcome)

推荐答案

函数作用域结束后,原始结构被破坏

the original struct get destroyed after the function scope ends

否,该结构的指针被破坏了.其余数据仍在堆中.如果在完成结果后不调用freeaddrinfo(),则可能会导致内存泄漏.

No, the struct's pointer is destroyed. The rest of the data is still in the heap. This would be a memory leak if you don't call freeaddrinfo() when you're finished with the result.

我想将该addrinfo存储在其他地方

i would like to store that addrinfo somewhere else

由于数据仍然存在,请随时复制指针;无需深层复制.从您的示例中:

Since the data still exists, feel free to copy the pointer; no need for a deep copy. From your example:

void GetAddrInfo(struct addrinfo **update)  /* pointer to pointer */
{
    struct addrinfo *res;
    getaddrinfo(xx,xx,xx,&res);
    *update=res;  /* save the pointer to the struct */
}

您只需使用以下命令调用此函数:

You would simply call this function with:

struct addrinfo *mycopy;
GetAddrInfo(&mycopy);

这篇关于getaddrinfo addrinfo结果在堆栈或堆中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆