Search code examples
clibcbsd

Implement of original strlcpy function on Libc


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

size_t  ft_strlcpy(char *dst, const char *src, size_t dstsize)
{
    unsigned int    i;
    unsigned int    dst_len;

    i = 0;
    dst_len = strlen(dst);
    if (dstsize > 0)
    {
        while (src[i] != '\0' && i < dstsize - 1)
        {
            dst[i] = src[i];
            i++;
        }
        dst[i] = '\0';
    }
    return (strlen(src));
}

int    main(void)
{
    char dst[100] = "HelloWorld!";
    char dst2[100] = "HelloWorld!";

    const char src[11] = "teststring";
    int dstsize = -1;
    printf("mine : %zu\n", ft_strlcpy(dst, src, dstsize));
    printf("%s\n", dst);
    printf("string.h : %zu\n", strlcpy(dst2, src, dstsize));
    printf("%s\n", dst2);


    return (0);
}

This code is my code of implementing strlcpy on my own.

but I have one doubt question.

when dstsize is negative number, my fucntion don't print any error message.

but original strlcpy print Tracetrap error(maybe SIGILL in linux. I'm using OS X)

error

I have searched most of bsd original c library github, but all of them work same as my code. I want to know the difference. how original strlcpy print error when dstsize is negative number?

This question's point is "how to print trace trap error when dstsize is negative number like original function?(I know it will be converted to size_t max number.)"


Solution

  • There is no reason to compute the length of the string in dst for strlcpy: dst_len = strlen(dst); is useless and counterproductive.

    Here is a modified version:

    size_t  ft_strlcpy(char *dst, const char *src, size_t dstsize)
    {
        size_t    i;
    
        i = 0;
        while (i + 1 < dstsize && src[i] != '\0') {
            dst[i] = src[i];
            i++;
        }
        if (i < dstsize) {
            dst[i] = '\0';
        }
        while (src[i] != '\0') {
            i++;
        }
        return i;
    }
    

    Regarding your question:

    how to print trace trap error when dstsize is a negative number?(I know it will be converted to size_t max number.)

    If the destination size passed by the caller is a negative number, ie: the result of some computation that produces or would produce a negative number using signed arithmetics, it is converted to size_t modulo SIZE_MAX + 1, hence the value is huge.

    You can detect this by comparison:

     if (dstsize > SIZE_MAX >> 1) {
         fprintf(stderr, "ft_strlcpy: huge dstsize indicates a negative value was passed: %zd\n", dstsize);
         abort();
     }