关于类型转换的问题
我对打字有疑问。这只是此处显示的一个虚拟程序。实际代码太大,无法发布。
typedef struct abc
{
int a;
}abc_t;
main()
{
abc_t *MY_str;
char *p;
MY_str = (abc_t *)p;
}
每当我运行质量分析检查工具时,我都会收到 2 级警告:
Casting to different object pointer type. REFERENCE - ISO:C90-6.3.4 Cast Operators - Semantics <next> Msg(3:3305) Pointer cast to stricter alignment. <next>
任何人都可以告诉我如何解决此问题吗?
I have questions about typecasting. This is just a dummy program shown here. The actual code is too big to be posted.
typedef struct abc
{
int a;
}abc_t;
main()
{
abc_t *MY_str;
char *p;
MY_str = (abc_t *)p;
}
Whenever I run the quality analysis check tool, I get a level 2 warning:
Casting to different object pointer type. REFERENCE - ISO:C90-6.3.4 Cast Operators - Semantics <next> Msg(3:3305) Pointer cast to stricter alignment. <next>
Can anyone please tell me how to resolve this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简单 - 您的静态分析工具(顺便说一句?)已确定
char*
没有特定的对齐要求(它可以指向内存中的任何位置),而abc_t*
> 可能有字对齐要求(int
必须位于 4/8 字节边界上)。实际上,由于
char*
位于堆栈上,因此它在大多数体系结构上都是字对齐的。您的工具看不到这一点。Simple - your static analysis tool (which, btw?) has decided that a
char*
does not have a particular alignment requirement (it could point anywhere in memory) whereas anabc_t*
likely has a word alignment requirement (int
must be on a 4/8 byte boundary).In reality, as the
char*
is on the stack, it will be word aligned on most architectures. Your tool cannot see this.在您的实现(可能还有许多其他实现)中,每个
int
必须位于可被sizeof int
整除的地址,该地址通常为 4。另一方面,
>char
可以位于任何地址。这就像将
3.25
分配给int
变量。这也是不可能的。因此,当您有一个坏指针时,您的机器可能会出现异常,并且从技术上讲,此代码会调用未定义的行为。
In your implementation (and probably many others) each
int
must be at an address that is divisible bysizeof int
, which is often 4.On the other hand, a
char
can be at any address.It's like assigning
3.25
to anint
variable. That's also not possible.So when you have a bad pointer, you will probably get an exception from your machine, and technically this code invokes undefined behavior.
char*
可以在任何字节边界上对齐,这意味着如果将其转换为结构,则可能无法满足该结构的对齐要求(例如 SIMD 类型所需的 16 字节边界)。a
char*
can be aligned on any byte boundary, which means if you cast it to a structure, the alignment requirements of that struct might not be met (such as 16 byte boundaries required for SIMD types).你的代码是无效的C。如果你发现自己在做这样的事情,这可能是更大的误解的结果。例如,我猜测您想从文件/套接字/等读取
abc_t
对象。并且您习惯于将char
指针传递给read
/recv
/whatever 函数。相反,您应该只声明一个abc_t
类型的对象,并将其地址传递给您正在使用的任何读取函数。Your code is invalid C. If you find yourself doing something like this, it's probably the result of a greater misunderstanding. For instance I'm guessing you want to read an
abc_t
object from a file/socket/etc. and you're used to passing achar
pointer to theread
/recv
/whatever function. Instead you should just declare an object of typeabc_t
and pass its address to whatever reading function you're using.