为 strncpy 创建包装器以插入终止 null

标签 c wrapper strncpy

我决定为 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/

相关文章:

c - strcpy()/uninitialized char pointer 这段代码背后的技巧是什么?

c - 在 C 中获取内置参数

C++ 使用指针地址打印 Char

c - C 运行时确定变量类型

ios - React Native 广告网络包装器

c - strncpy() 替代方案 - 每个版本有什么优点?

c - 在套接字上使用 O_NONBLOCK 后,有没有办法避免 HUP?

c# - 为 COM DLL 创建 .NET 包装器的工具?

C# 选项以最好地使用具有 1000 个函数的 C++ DLL

c - 我的字符串连接每次结果都会加倍,为什么?