My own strlcat() Function

Coding my own version of the non-standard strlcat() function proved to be a bit more work than I anticipated. That’s because I also had to code my own versions of the strcpy() and strlen() functions to make the thing work.

The reason I couldn’t use the standard library versions of strcpy() and strlen() is that the string.h header also brings in the definition of strlcat(); the two prototypes would conflict. Further, I chose to code my own version of strcpy() as opposed to using the strlcpy() code from a Lesson I wrote a few weeks back.

If strlcat() isn’t available in the library, you need not code your own strcpy() and strlen() functions as there would be no conflict in the string.h header.

Thanks to the research done from last week’s Lesson, I know the return value of the strlcat() function: the combined length of both the source and destination strings:

d_len = strlen(dst);
s_len = strlen(src);

Further, the d_len value is used to find the offset in the dst buffer where the string is appended. Here is my version of the strlcat() function:

size_t strlcat(char *restrict dst, const char *restrict src, size_t dstsize)
{
    int d_len,s_len,offset,src_index;

    /* obtain initial sizes */
    d_len = strlen(dst);
    s_len = strlen(src);

    /* get the end of dst */
    offset = d_len;

    /* append src */
    src_index = 0;
    while( *(src+src_index) != '\0' )
    {
        *(dst+offset) = *(src+src_index);
        offset++;
        src_index++;
        /* don't copy more than dstsize characters
           minus one */
        if( offset==dstsize-1)
            break;
    }
    /* always cap the string! */
    *(dst+offset) = '\0';

    return( d_len+s_len );
}

The function’s while loop copies characters from src to dst until the end of string src:

*(dst+offset) = *(src+src_index);

Variables offset and src_index track the positions within each buffer, with offset compared against argument dstsize to check for overflows:

if( offset==dstsize-1)
    break;

The code’s main() function is the same as presented last week. To view the full code, including my versions of strcpy() and strlen(), click here (GitHub).

Here’s a sample run:

This is a poten
Value returned: 33
String truncated

The output is identical to the test code presented in last week’s Lesson. When the buffer size is changed to 64, the result is also identical:

This is a potentially long string
Value returned: 33
String was fully copied

I thought this reverse engineering task would be more difficult than the job I did for strlcpy(), but I was wrong. (Well, save for also re-writing the strcpy() and strlen() functions.) The key to emulating a library function is to run multiple tests on the original. Try to discern what the function is doing internally. The goal is to mimic that behavior so that you can use the function on a C compiler that’s standard, or one that lacks the function you’re trying to emulate.

Leave a Reply