Why memset sockaddr_in to 0

Is there any final guide that says we should initialize the sockaddr_in structure to zero for a reason?

// IPv4 AF_INET sockets: struct sockaddr_in { short sin_family; // eg AF_INET, AF_INET6 unsigned short sin_port; // eg 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 at real code or an example or books, it always has a 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 say that the element char sin_zero[8] exists for filling and should be set to zero, but why reset the rest. Especially when they are initialized in most cases in the next few lines of the declaration. Even about the sin_zero member in the programming guide, beej said it was not necessary to reset them anymore . I was looking for an explanation, but nothing worked. This stack overflow issue has several different suggestions for initialization itself, but does not explain why it is necessary to reset.

Is this an outdated practice, or is there some real reason I'm missing out on? Any link is appreciated.

+7
c ++ sockets network-programming memset
source share
1 answer

Think of it as the default constructor, i.e. it initializes the data with known values ​​(in this case, 0). This can help alleviate the problems associated with uninitialized data when using PODs, for example, forgetting to set the member, although memset not really necessary, and you can simply initialize the structure with sockaddr_in foo{}; (By the way, this also leads to better assembly code behind the scenes, since the compiler can movq 0 all instead of calling memset , and not that it will make a big difference in 99% of cases).

If you are absolutely sure that you are going to install all the members, then this is not strictly necessary, although it can help catch errors earlier if you forgot to initialize something.

+6
source share

All Articles