Strict aliasing rules for allocated objects

十年热恋 提交于 2019-12-22 10:38:09

问题


C99 6.5/6 The effective type of an object for an access to its stored value is the declared type of the object, if any. 75)

If a value is stored into an object having no declared type through an lvalue having a type that is not a character type, then the type of the lvalue becomes the effective type of the object for that access and for subsequent accesses that do not modify the stored value.

If a value is copied into an object having no declared type using memcpy or memmove, or is copied as an array of character type, then the effective type of the modified object for that access and for subsequent accesses that do not modify the value is the effective type of the object from which the value is copied, if it has one. For all other accesses to an object having no declared type, the effective type of the object is simply the type of the lvalue used for the access.

75) Allocated objects have no declared type.

As stated in C99, the effective type of static objects is their declared type.

How do allocated objects get their effective types?

For example:

int *p = malloc(100 * sizeof(int));

Why don't they have a declared type to begin with?


回答1:


An allocated object hasn't got any declared type, so its effective type is the type of the lvalue used for the access. With this single statement, p hasn't effective type:

#include <stdlib.h>
int *p = malloc(100 * sizeof(int));

Otherwise, it will have one with the next access:

/* Effective type of p: unsigned int */
*(unsigned int *)p = 20U;


来源:https://stackoverflow.com/questions/13723839/strict-aliasing-rules-for-allocated-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!