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

From: kevin lyda (kevin at domain suberic.net)
Date: Fri 04 May 2001 - 13:17:43 IST


On Fri, May 04, 2001 at 11:52:09AM +0000, Conor Daly wrote:
> 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?

either you don't understand or you're leaving out information. so...

#define STRSIZE 80
char *
strdup2(char *s1, char *s2)
{
    char *s;

    if ((s=(char *)malloc(STRSIZE + 1)) == NULL) {
        return NULL;
    }
    /* the following initialises the string. s[0]=0;s[STRSIZE]=0; *
     * would work too. */
    memset(s, 0, STRSIZE + 1);
    /* from here on in we don't let str* routines near s[STRSIZE] *
     * so we know it will stay 0. */
    strncpy(s, s1, STRSIZE);
    strncpy(s, s2, STRSIZE - strlen(s));
    return s;
}

strlen works by counting chars until it reaches '\0'. therefore don't use
    it if you're not sure the string is null terminated.
sizeof(char) is not required.

kevin

-- 
kevin at domain suberic.net          "nobody likes a monkey on their back.  i had
fork()'ed on 37058400      three.  they were cramping my style.  it was
meatspace place: work      time to get rid of them."
http://suberic.net/~kevin                --porter, "payback"


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