gpt4 book ai didi

你能假设类型转换指针是安全的吗?

转载 作者:太空狗 更新时间:2023-10-29 15:19:54 25 4
gpt4 key购买 nike

我从很多人那里听说,您不能保证类型转换会无损执行。只有在您不了解您的处理器时,即您还没有验证用于您的数据类型的字节数时,这是否才是正确的?让我举个例子:

如果您执行以下操作:

typedef struct
{
int i;
char c;
float f;
double d;
} structure;

size_t voidPtrSz = sizeof(void *);
size_t charPtrSz = sizeof(char *);
size_t intPtrSz = sizeof(char *);
size_t floatPtrSz = sizeof(float *);
size_t doublePtrSz = sizeof(double *);
size_t structPtrSz = sizeof(structure *);
size_t funcPtrSz = sizeof(int (*)(float, char));

printf("%lu\n", voidPtrSz);
printf("%lu\n", charPtrSz);
printf("%lu\n", intPtrSz);
printf("%lu\n", floatPtrSz);
printf("%lu\n", doublePtrSz);
printf("%lu\n", structPtrSz);
printf("%lu\n", funcPtrSz);

...输出如下...

4
4
4
4
4
4
4

您能否假设在所有情况下都可以将特定数据类型指针安全地转换为另一种数据类型指针?例如,如果您执行此操作:

int foo(float, char)
{
}

void *bar(void)
{
return (void *)foo;
}

int (*pFunc)(float, char) = bar();

你能确定 pFuncfoo 的地址吗?

最佳答案

关于你的具体代码示例,我们引用C99语言标准的6.3.2.3节:

A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

请注意,指向函数的指针与指向对象的指针不同。唯一提到的指针到函数的转换是:

A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.

因此您的代码示例调用了未定义的行为。

如果我们避免函数指针转换,下面的段落解释了一切:

A pointer to an object or incomplete type may be converted to a pointer to a different object or incomplete type. If the resulting pointer is not correctly aligned for the pointed-to type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer.

注意:指针类型之间的转换与转换和然后取消引用是不同的问题(一般来说,只有在转换为 char * 时才有效) 然后取消引用。)

关于你能假设类型转换指针是安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20402814/

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