Search code examples
cwrapperstrncpy

Creating a Wrapper for strncpy to Insert Terminating null


I have decided to make a wrapper for strncpy as my source code requires me to do a lot of string copies. And I want to ensure that the string is terminated if the source is equal or greater than the destination.

This code will be used in production, so I just want to see if there are any potential dangers using this wrapper.

I have never done wrappers before so I am trying to make it perfect.

Many thanks for any advice,

/* Null terminate a string after coping */
char* strncpy_wrapper(char *dest, const char* source, 
                      const size_t dest_size, const size_t source_size)
{
    strncpy(dest, source, dest_size);
    /* 
     * Compare the different length, if source is greater
     * or equal to the destination terminate with a null.
     */
    if(source_size >= dest_size)
    {
        dest[dest_size - 1] = '\0';
    }

    return dest;
}

==== Edited updated ====

/* Null terminate a string after coping */
char* strncpy_wrapper(char *dest, const char* source, 
                      const size_t dest_size)
{
    strncpy(dest, source, dest_size);
    /* 
     * If the destination is greater than zero terminate with a null.
     */
    if(dest_size > 0)
    {
        dest[dest_size - 1] = '\0';
    }
    else
    {
        dest[0] = '\0'; /* Return empty string if the destination is zero length */
    }

    return dest;
}

Solution

  • Check dest_size before accessing the array or you'll get into trouble:

    if (dest_size > 0) {
        dest[dest_size - 1] = '\0';
    }
    

    Actually, now that I think of it, it's probably better to just die:

    if (dest_size == 0) {
        fputs(stderr, "strncpy(x,y,0)");
        exit(1);
    }
    

    Otherwise, you'll have the same problem as with the original strncpy(), that dest may not be terminated if dest_size is 0.