Question

What is the reason for strlcpy.c to copy the arguments into local variables:

size_t
strlcpy(char *dst, const char *src, size_t siz)
{
    char *d = dst;
    const char *s = src;
    size_t n = siz;

    /* Copy as many bytes as will fit */
    if (n != 0) {
        while (--n != 0) {
            if ((*d++ = *s++) == '\0')
                break;
        }
    }

    /* Not enough room in dst, add NUL and traverse rest of src */
    if (n == 0) {
        if (siz != 0)
            *d = '\0';      /* NUL-terminate dst */
        while (*s++)
            ;
    }

    return(s - src - 1);    /* count does not include NUL */
}

Update

I added the body.

Was it helpful?

Solution

One very common reason is that the variables are modified in the function, and then used in an expression together with the arguments.

For example, the function might modify the variable n, and later do e.g. return siz - n;.

OTHER TIPS

Actually in the rest of the code siz and src are needed to calculate some stuff:

/* Not enough room in dst, add NUL and traverse rest of src */
if (n == 0) {
    if (siz != 0)
        *d = '\0';      /* NUL-terminate dst */
    while (*s++)
        ;
}

return(s - src - 1);    /* count does not include NUL */

But I can't see why dst is copied locally. Maybe just for symmetry.

For dst and d, I think, just for simmetry. For the other variables they are used in "code" both with their initial and updated values.

At least for the src argument, it's used to calculate the length to return. The final line of that function shows that:

return(s - src - 1);

In terms of the dst argument, it's not actually needed but it may have been done for consistency. It probably doesn't matter because a decent optimising compiler will probably not be affected by this seemingly extra variable.

size_t
strlcpy(char *dst, const char *src, size_t siz)
{                     ^-------------------------->constant so must not be modified. that's why a temp variable is needed for modification.     
    char *d = dst;     <-- useless may be.
    const char *s = src;
    size_t n = siz;      

    /* Copy as many bytes as will fit */
    if (n != 0) {        
        while (--n != 0) {
            if ((*d++ = *s++) == '\0')
                break;
        }
    }

    /* Not enough room in dst, add NUL and traverse rest of src */
    if (n == 0) {                    <-- new n arg.
        if (siz != 0)              <---  original siz arg
            *d = '\0';      /* NUL-terminate dst */
        while (*s++)
            ;
    }

    return(s - src - 1);    /* count does not include NUL */  <-- using the original and modified values of s and src together.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top