Tom St Denis said:
What happens here?
It appears that servIP is allocated immediately after myport in memory.
Also the correct usage of strncpy [sadly] is this
memset(dest, 0, sizeof dest);
strncpy(dest, src, sizeof(dest) - 1);
Which is really F'ing stupid IMHO. A call to strncpy(dest, src,
sizeof dest) should guarantee that dest is NUL terminated...
It's not a bug, it's a feature. No, really.
strncy's source buffer is expected to contain an ordinary C string,
consisting of a sequence of non-null characters terminated by and
including a null character (with zero or more bytes of ignored
garbage following the terminator).
The target buffer, however, contains a data structure that's similar
to a C string, but subtly different. It consists of a sequence of
non-null characters foolowed by zero or more null characters, padding
to the end of the buffer. If there are one or more terminating
null characters, this can be treated as a string; if not, it can't.
This data structure is not used very often, but it is used sometimes,
which is why strncpy() exists. For example, I believe that early
Unix systems used it to store file names.
The real problem is that the name strncpy() implies that it has the
same relationship to strcpy() that strncat() has to strcat() (namely
that strncat() is a "safer" version of strcat() that lets you specify
the maximum size of the destination buffer). But strncpy() is *not*
a safer strcpy(); it's a function that does something similar,
but in a way that makes it very easy to shoot yourself in the foot.
If you don't specifically need to deal with this particular data
structure, don't use strncpy(). (Most programmers can safely ignore
all but the last three words of that sentence.)
It would have been nice if we had a standard strncpy() function
that actually does what a lot of people expect it to do, and if
the strncpy() we have were either given a different name or removed
from the standard. But it's about 20 years too late for that.
[...]
N.B. The man page for strncpy in Ubuntu has a typo ... the string is
nul terminated not null ...
That's not a typo; "null terminated" is correct. ("nul terminated"
would also be correct.) It means that the string is terminated
by a null character, a term used by the C standard. (The man page
uses the term "null byte", which is also valid.)