Sometimes, we get a submission and the submitter provides absolutely no context. Sometimes, the snippet is even really short, or the problem is "subtle" in a way that means we can't spot it when skimming the inbox.
Which is why this submission from "Bus Error" has been sitting in the inbox for seven years, and why just today, as I was skimming old submissions, I finally saw what was great about this little block of C-code.
struct sockaddr_in serv_addr;
memset(&serv_addr, '0', sizeof(serv_addr));
The goal of this block of code is to ensure that the serv_addr
variable is set to all zeros before it gets used elsewhere. But instead of doing that, this sets it to all '0'
- the character, not the number. So instead, this initializes all the memory to 0x30
.
Now, given that the first field in a sockaddr_in
is the address family, which must be AF_INET
on Linux, this is definitely not going to work. Even if it was actually memsetting to 0
, it still wouldn't be a correct thing to do in this case. Plus, there's a whole family of methods meant to initialize this structure to the correct usable values, so this memset shouldn't be there at all.
Without context, I suspect this was programming by incantation: someone learned the hard way that variables in C don't start with a known value, so they decided to make sure that every variable they declared got zeroed out. It was a magic spell that solved a problem they didn't understand.