Please help debug my socket code!

Joe Nelson joe at begriffs.com
Thu Feb 14 06:19:50 UTC 2019


> Could this problem be caused by missing initialization of the addrinfo
> struct?

Thanks for taking the time to look at my code. I found the problem and
it was in a different part. I'll reply to my previous message with
details about the fix. Wanted to comment on your suggested patch though:

> + memset(&hints, 0, sizeof(hints));

I'm actually initializing hints with `hints = {0}` because I think it's
a more portable way to zero out all the fields. Using memset makes
everything *bitwise* zero, but for pointers or floating point that
doesn't always represent NULL or 0.0 on all platforms. The technique
with {0} treats all fields correctly depending on their types. I think
it works in both C89 and C99. The language spec for each version says
this:

C89 §6.5.7

If there are fewer initializers in a brace-enclosed list than there
are members of an aggregate, the remainder of the aggregate shall be
initialized implicitly the same as objects that have static storage
duration.

C99 §6.7.8

21 If there are fewer initializers in a brace-enclosed list than there
   are elements or members of an aggregate, or fewer characters in a
   string literal used to initialize an array of known size than there
   are elements in the array, the remainder of the aggregate shall be
   initialized implicitly the same as objects that have static storage
   duration.

Just to verify, I compiled the following program in clang with
"-std=c89" and it worked.

  #include <stdio.h>
  
  struct foo
  {
  	int a;
  	int *b;
  };
  
  int main(void)
  {
  	struct foo f = {0};
  
  	printf ("%d %p\n", f.a, f.b);
  	return 0
  }


More information about the Friends mailing list