我正在查看一些简洁的示例代码,展示如何在特定硬件平台上复制 float 而不会遇到内存对齐问题。我注意到它没有使用 sizeof()
:
uint8_t mybuffer[4];
float f;
memcpy(&f, mybuffer, 4)
下一个问题是使用 sizeof()
什么导致微软的部分答案 memcpy_s但这是一种运行时方法,需要返回检查。
稍微超出我引用的代码片段,对于可以在编译时正确确定源和目标大小的特定情况,是否有紧凑/单行 (例如,为了保持示例代码简短)等同于 memcpy()
确保长度相同,如果不相同则终止编译并显示一条有用的消息?一个可以避免 ARR01-C. Do not apply the sizeof operator to a pointer when taking the size of an array 陷阱的人会很好。
此处与 memcpy(), what should the value of the size parameter be? 有一些重叠
最佳答案
-
What's the modern, portable, safe equivalent of memcpy with compile-time checks in C?
memcpy
现代、便携且安全。不存在您应该使用的替代品。如果您使用 Microsoft 逻辑,那是
memcpy
的错误,无能的程序员将空指针传递给它。但此类错误应该通过在传递输入之前检查输入的健全性来修复,而不是通过更改memcpy
。memcpy_s
被视为已弃用,应避免使用 C11 边界检查接口(interface)中的所有内容,因为不存在对它的编译器支持。 Visual Studio 等危险的编译器也使其不可移植,因为它们甚至不遵循 C 标准 Annex K,而是发明了自己的不兼容版本。我的建议是将每个以_s
结尾的函数视为安全隐患。 -
is there a compact/single line (e.g. to keep that example code short) equivalent of memcpy() that ensures that the lengths are identical and terminates compilation with a helpful message if not?
是的。
memcpy(&f, mybuffer, sizeof(f))
-
One that avoids the pitfalls of ARR01-C. Do not apply the sizeof operator to a pointer when taking the size of an array would be nice
CERT 规则仅适用于不知道函数参数数组衰减如何工作的程序员。解决方案是教育人们,而不是假设每个使用您的代码库的程序员都是无能的。此外,这是静态分析器会捕获的典型错误 - 启用静态分析实际上可能正是 CERT 规则存在的原因。
如果您知道自己在做什么,您可以在函数内部使用
sizeof
。每个以数组作为参数的函数也有一个大小。使用那个尺寸。因此,如果您有这样的代码:void foo (size_t n, float array[n]);
那么您可以在该函数内执行sizeof(float[n])
就好了。作为替代方案,还有另一种有点晦涩的版本,有时由安全标准插入。如果您将函数更改为使用数组指针,
void foo (size_t n, float(*array)[n])
,您可以在里面执行sizeof(*array)
那个功能。我们还可以使用数组指针来提高类型安全性:void foo (float(*array)[5]); ... float arr[4]; foo(&arr); // compiler error
缺点:语法复杂得多,我们失去了使
const
正确参数的能力。
关于c - 什么是现代、可移植、安全的 memcpy 等价物,在 C 中进行编译时检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56886064/