我决定制作一个包装器,strncpy
因为我的源代码需要我做很多字符串副本。如果源等于或大于目标,我想确保字符串终止。
这段代码将在生产中使用,所以我只想看看使用这个包装器是否有任何潜在的危险。
我以前从未做过包装,所以我试图让它变得完美。
非常感谢您的任何建议,
/* 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;
}
====编辑更新====
/* 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;
}