首页 > 解决方案 > 为 C 创建一个安全的 strcpy,以处理无法检查源/目标长度的问题

问题描述

据我了解,字符串/缓冲区长度的 C 目标是相信函数的用户提供正确的源/目标长度作为参数?我正在尝试编写类似于 strlcpy 的 strcpy,但它可以避免未定义的行为写入未分配给该目标缓冲区的内存。

我下面的工作是我到目前为止所做的,我只能看到一种方法来做到这一点,它相信目标大小不会要求在比目标缓冲区实际拥有的空间更大的空间中进行操作。

反正有没有改进这个/更好的选择?

static bool s_strcpy(const char* source, char* destination, size_t dest_length, size_t copy_length)
{
    if ((NULL == source) || (NULL == destination) || (dest_length <= 0) || (copy_length <= 0))
    {
        return false;
    }

    if (dest_length < copy_length)
    {
        copy_length = dest_length;
    }

    int err = 0;
    err |= memset_s(destination, dest_length, 0, dest_length);
    err |= memcpy_s(destination, dest_length,source, copy_length);
    if (err)
    {
        perror("Error when copying strings in s_strcpy");
        return false;
    }
    destination[dest_length-1] = '\0';
    return true;
}

标签: cmemoryerror-handlingbuffer

解决方案


推荐阅读