gpt4 book ai didi

检查 GUID 是否为空(在 C 中)

转载 作者:可可西里 更新时间:2023-11-01 14:37:48 27 4
gpt4 key购买 nike

我想检查一个 GUID 结构是否为空/所有字段都为 0。这是我写的代码:

#include <windows.h>

static BOOL IsEmptyGuid(const GUID * const pGuid)
{
return \
(pGuid->Data1 == 0) &&
(pGuid->Data2 == 0) &&
(pGuid->Data3 == 0) &&
#ifdef _WIN64
(*(DWORD64 *)pGuid->Data4 == 0);
#else
(*(DWORD *)pGuid->Data4 == 0) && (*(DWORD *)(pGuid->Data4 + 4) == 0);
#endif
}

/* GUID definition from MSDN
typedef struct _GUID {
DWORD Data1;
WORD Data2;
WORD Data3;
BYTE Data4[8];
} GUID;
*/


int main() {
GUID guid1;
guid1.Data1 = 0;
guid1.Data2 = 0;
guid1.Data3 = 0;
memset(guid1.Data4, 0x0, 8);

printf("Result: %u\n", IsEmptyGuid(&guid1));
}

检查字段 Data4 是否等于 0 的更安全方法是遍历每个字节并检查其值。但是,我发现上面的代码更具表现力。

我想知道,这是正确的吗?安全吗?

谢谢!

最佳答案

代码不正确。它违反了严格的别名规则(N1570 §6.5 p7),导致未定义的行为。

An object shall have its stored value accessed only by an lvalue expression that has one ofthe following types: 88)

  • a type compatible with the effective type of the object,
  • a qualified version of a type compatible with the effective type of the object,
  • a type that is the signed or unsigned type corresponding to the effective type of theobject,
  • a type that is the signed or unsigned type corresponding to a qualified version of theeffective type of the object,
  • an aggregate or union type that includes one of the aforementioned types among itsmembers (including, recursively, a member of a subaggregate or contained union), or
  • a character type.

88) The intent of this list is to specify those circumstances in which an object may or may not be aliased.

确切地说,UB 发生在您使用非匹配类型取消引用指针时:

DWORD64 * temp = (DWORD64 *)pGuid->Data4; // Allowed, but implementation defined
DWORD64 temp2 = *temp; // Undefined behaviour

使用循环分别检查每个元素,或与 memcmp 比较相同大小的零填充数组。


如评论中所述,某些编译器允许禁用严格别名,但应避免这样做,因为它会降低代码的可移植性,并且您仍然存在潜在的对齐问题。

关于检查 GUID 是否为空(在 C 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45411195/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com