The bind() function gets const struct sockaddr *addr as one of parameters. Can I pass a temp sockaddr structure, that will be deleted immediately after bind() calling?
void bindMe(int socket) {
struct sockaddr_in addr = {...};
bind(socket, (struct sockaddr_in*)&addr, sizeof(sockaddr_in));
}
// addr is no more exist after function calling,
// but I still want to work with the socket.
Also, there is a lot of function in POSIX take pointer to structs. How can I determine if I can free the struct after function calling?
Yes, you can do that.
bindis a synchronous system call, so once it returns, the kernel is all done with the parameters.If the socket is non-blocking and
bindreturnsEINPROGRESSto indicate that the bind is happening asynchronously, it’s still safe to free the struct. The kernel copies the struct internally while the operation completes asynchronously.Read the documentation. Most POSIX functions are synchronous, and the parameters can safely be deallocated after the function returns, but that’s not always true. If you’re unsure, read the documentation. And obviously if you have multiple threads in your program, you shouldn’t be concurrently modifying the data from another thread while an API call is in progress.