我决定为 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;
}
最佳答案
您不需要检查源是否大于目标,只需始终将目标中的最后一个字符设为“\0”即可。
关于为 strncpy 创建包装器以插入终止 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1184291/