简体   繁体   English

为什么将sockaddr_in设置为0

[英]Why memset sockaddr_in to 0

Is there any definitive guide that says we have to initialize the sockaddr_in struct to zero for a particular reason? 是否有任何权威指南说,由于特定原因,我们必须将sockaddr_in结构初始化为零?

// IPv4 AF_INET sockets:
struct sockaddr_in {
    short            sin_family;   // e.g. AF_INET, AF_INET6
    unsigned short   sin_port;     // e.g. htons(3490)
    struct in_addr   sin_addr;     // see struct in_addr, below
    char             sin_zero[8];  // zero this if you want to
};

Whenever I looked in real code or example or books it always has the code structure similar to the following: 每当我查看真实的代码或示例或书籍时,它始终具有类似于以下内容的代码结构:

struct sockaddr_in foo;
memset(&foo, 0, sizeof(foo)); 
foo.sin_port = htons(1025);
foo.sin_family = AF_INET;
inet_pton(AF_INET, "10.0.0.1", &foo.sin_addr);

I understand that some sources says that the char sin_zero[8] member is there for padding and should be set to zero but why zeroing the rest. 我知道有些消息说char sin_zero[8]成员可以在那里填充,应该将其设置为零,但是为什么要将其余的零。 Especially when they are initialized in most cases within next few lines of declaration. 特别是在大多数情况下,在声明的后几行中初始化它们时。 Even about sin_zero member the beej programming guide said it is not mandatory to zero them out anymore . 甚至对于sin_zero成员,beej编程指南也表示不再强制将它们归零 I have searched for an explanation but nothing to the point turned up. 我一直在寻找解释,但没有提出要点。 This stack overflow question has some different suggestions on the initialization itself but does not explain why the zeroing is necessary. 这个堆栈溢出问题对初始化本身有一些不同的建议,但是没有解释为什么需要归零。

Is it a legacy practice or there are some real reason I am missing out? 这是一种传统做法还是我错过了某些真实原因? Any reference is appreciated. 任何参考表示赞赏。

Think of it as a default constructor, ie it initializes the data to known values (0 in this case). 将其视为默认构造函数,即它将数据初始化为已知值(在这种情况下为0)。 This can help mitigate issues related to non-initialized data when using PODs, like forgetting to set a member, although memset isn't really necessary and you can just value-initialize the struct with sockaddr_in foo{}; 这可以帮助减轻使用POD时与未初始化数据相关的问题,例如忘记设置成员,尽管memset并不是真正必要的,并且您可以使用sockaddr_in foo{};值对结构进行初始化sockaddr_in foo{}; (incidentally this also results in better assembly code behind the scenes as the compiler can movq 0 everything instead of calling memset , not that it'll make much difference in 99% of cases). (顺便说一句,这也可以在幕后产生更好的汇编代码,因为编译器可以移动所有内容而不是调用memset movq 0而不是在99%的情况下有很大的不同)。

If you are absolutely sure you are going to set all members then it isn't strictly necessary, although it can help catch bugs earlier if you forget to initialize something. 如果您完全确定要设置所有成员,那么这不是严格必要的,尽管如果您忘记初始化某些内容,它可以帮助更早地捕获错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM