Non-Standard Function: strlcpy()

I though writing a substitute strlcpy() function would be easy. Boy was I wrong!

First, a look at the strlcpy() function’s prototype:

size_t strlcpy(char * restrict dst, const char * restrict src, size_t dstsize);

For comparison, here is the man page definition for the strcpy() function:

char * stpcpy(char * dst, const char * src);

In both functions, the contents of string src are copied into buffer dst. With the strlcpy() function, however, only dstsize characters maximum are copied, and the value returned is the size of string src. (The value returned is always the size of string src regardless of how many characters are copied.)

Oh, and the nerds argue over whether the value returned is really a size_t value or an int. Nerds.

My first attempt was simple enough: Copy up to dstsize characters from src to dst, terminating the operation when the null character is found in string dst or the value of dstsize was reached. Easy.

But.

The code seemed to run too well. Plus I had concerns about the function’s return value. So I wisely decided to run a control program first, just to monitor the behavior of the real strlcpy() function. Here is the code:

#include <stdio.h>
#include <string.h>

void test(int size)
{
    char string[] = "Hello there, Venus";
    char buffer[19];
    int r;

    r = strlcpy(buffer,string,size);

    printf("Copied '%s' into '%s', length %d\n",
            string,
            buffer,
            r
          );
}

int main()
{
    test(19);
    test(10);
    test(1);
    test(0);

    return(0);
}

The main() function runs four tests, each with a different value for the number of characters to copy. In the test() function, array string[] is copied up to size characters into buffer. Output generated offers the original string, the copy, and the value returned by the strlcpy() function. These are all valid data points I must know if I am to properly reverse engineer the function. Here’s the test run;

Copied 19 characters from 'Hello there, Venus' into 'Hello there, Venus', length 18
Copied 10 characters from 'Hello there, Venus' into 'Hello the', length 18
Copied 1 characters from 'Hello there, Venus' into '', length 18
Copied 0 characters from 'Hello there, Venus' into '', length 18

In the first test, only 18 characters are copied because the null character is encountered.

The second test copies 10 characters (9 plus the null character).

The third and fourth tests copy no characters.

In each test, the value 18 is returned, which is the length of the string[] array as would be reported by the strlen() function; the string’s buffer size is 19 when you include the null character.

With this information in hand, I was better able to craft my version of the strlcpy() function, ensuring that it exhibited the same behavior as the actual function. I present my solution in next week’s Lesson.

Leave a Reply