Re: [ILUG] Re: C string concat question ??

From: Conor Daly (conor.daly at domain met.ie)
Date: Fri 04 May 2001 - 12:52:22 IST


On Thu, May 03, 2001 at 10:47:54AM +0100 or thereabouts, Lars Hecking wrote:
>
> As a side note, I'd generally stay away from strcpy() and strcat().
> It is estimated that about 80% of all security vulnerabilities are
> buffer overflows.
>
> If your OS supports it, use strlcpy() and strlcat() [OBSD 2.4+, FBSD 3.3+,
> Solaris 8+, dunno about others].
> Else, use at least strncpy() and strncat(), and make sure the result is
> null-terminated.

Excerpt from "man srtncpy"

     strcat() appends a copy of string src, including the ter-
     minating null character, to the end of string dst.
     strncat() appends at most n characters. Each returns a
     pointer to the null-terminated result. The initial charac-
                     ^^^^^^^^^^^^^^^^^^^^^^
     ter of src overrides the null character at the end of dst.

This suggests that strncat() null terminates in every case.

     strcpy() copies string src to dst including the terminating
     null character, stopping after the null character has been
     copied. strncpy() copies exactly n bytes, truncating src or
     adding null characters to dst if necessary. The result will
     not be null-terminated if the length of src is n or more.
                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

My reading of this is that

only strncpy() needs to be followed by a null terminator and only if it
reads less than the length of src. so, assuming

char *src;

strncpy(dest, src, strlen(src) * sizeof(char));

dest will be null terminated. Or does strlrn() leave out the null
terminator when returning a length?

Conor

--
Conor Daly 
Met Eireann, Glasnevin Hill, Dublin 9, Ireland
Ph +353 1 8064217 Fax +353 1 8064275
------------------------------------
 10:20am  up 23 days, 19:31,  7 users,  load average: 1.00, 1.00, 1.00


This archive was generated by hypermail 2.1.6 : Thu 06 Feb 2003 - 13:10:11 GMT