英文:
When is it safe to free sockaddr passed to bind?
问题
Bind 函数期望接收一个指向 struct sockaddr
的指针 (https://man7.org/linux/man-pages/man2/bind.2.html)。在调用 bind
后立即释放这个结构体是安全的吗,还是只有在套接字关闭时才安全释放它?
如果在调用 bind
后立即释放这个结构体是安全的,那么内核是否会保留地址的副本?
英文:
Bind expects a pointer to struct sockaddr
(https://man7.org/linux/man-pages/man2/bind.2.html). Is it safe to free this structure immediately after the call to bind
or is it safe to free this only when the socket is closed?
If it is safe to free the structure immediately after the call to bind
, does the kernel keep a copy of the address?
答案1
得分: 2
你可以在调用后立即释放它。
通常,sockaddr
或sockaddr_in
在堆栈上声明。但是,如果你通过指针传递地址,你可以在bind
返回后立即释放它。对于其他套接字函数,比如connect
和sendto
,情况也是一样的。
英文:
You can free it immediately after the call.
Usually the sockaddr
or sockaddr_in
is declared on the stack. But if you're passing addresses around by pointer, you're ok free it immediately after bind
returns. Same holds true for other socket functions like connect
and sendto
.
答案2
得分: 2
这是安全的释放。如您可以在Linux源代码中的注释中看到的那样,该结构由内核复制。
我们在调用协议层之前将套接字地址移动到内核空间(还检查地址是否正常)。
英文:
It is safe to free. As you can see in the comments to the Linux source for the syscall, the structure is copied by the kernel.
> * We move the socket address to kernel space before we call * the
> protocol layer (having also checked the address is ok).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论