ant2009
ant2009

Reputation: 22516

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;
}

Upvotes: 1

Views: 772

Answers (5)

Jonathan Leffler
Jonathan Leffler

Reputation: 753805

You should investigate the semi-standard BSD functions strlcpy() and strlcat().

You should consider whether the ISO TR24731 functions such as strncpy_s() are appropriate and available where you need them.

Upvotes: 2

sud03r
sud03r

Reputation: 19759

if dest_size is the number of characters to be copied and source_size is the number of characters in source string.
you should try this:


 size_t numchars = dest_size > source_size ? source_size : dest_size;
 strncpy(dest,source,numchars) ;
 dest[numchars] = 0 ;

Upvotes: 1

Inshallah
Inshallah

Reputation: 4814

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.

Upvotes: 2

Mehmet Ergut
Mehmet Ergut

Reputation: 1094

If you don't have any constraints on the allocation of the buffer, strndup could be more appropriate.

It will allocate and copy at most len chars, and always terminate with NULL.

Upvotes: 1

Martlark
Martlark

Reputation: 14581

You don't need to check that source is greater than destination just always make the last char in the dest a '\0'.

Upvotes: 3

Related Questions