One (repeated) mistake is:
nbytes_read=recv(sclient,(char *)date,sizeof(date),0);
recv()
does not null terminate. This means date
will not have a null terminator if sizeof(date)
bytes is read. This is a problem when a non-null terminated string is passed as an argument to printf()
with "%s"
format specifier. If the string is non-null terminated you may see garbage characters appearing after the actual string data. You need to read one less than the target buffer and null terminate or use the format specifier "%*.s"
that does not require null termination:
printf("%.*s", n, s); /* Prints first 'n' bytes from 's'. */
Note you can initialise a char[]
to all nulls instead of using a for
:
char date[8] = "";
or you can use memset()
.