c - 为 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;
}
解决方案
推荐阅读
- c# - 当端口作为 HTTP 访问时,Bouncy Castle 的 TlsServerProtocol.Accept() 挂起
- python - 从现在开始获取“几小时前”的日期
- java - RecyclerView 在不同的活动中将项目添加到我的数组列表并更新 recyclerview.adapter
- java - 如何在 Spring Boot 应用程序中为 @Scheduled cronjob 编写集成测试?
- python - 跳线?聊天室应用程序中的线程问题
- linux - 在 snmp 中为我的扩展 OID 设置一个值
- python - 如何使用 Python 以更快的方式将 csv 文件加载到 Oracle 表中
- typescript - 带有 TypeScript 不兼容类型错误的 Mobx
- elasticsearch - 分段和查询缓存 elasticsearch
- java - 从地图列表中提取所有字符串值