Hello,
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.
As 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 tyring to make itI 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;
}