Skip to content

UB19⚓︎

Author: Kai Xu

Definition⚓︎

A non-array lvalue with an incomplete type is used in a context that requires the value of the designated object (6.3.2.1).

需要指定对象值的地方使用具有不完整类型的非数组左值

Description⚓︎

lvalue: "An lvalue is an expression (with an object type other than void) that potentially designates an object(6.3.2.1)"

Object: "region of data storage in the execution environment, the contents of which can represent values(3.15.1)"

Incomplete Type:

  1. The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.(6.2.5.24)
  2. An array type of unknown size is an incomplete type.(6.2.5.27)
  3. A structure or union type of unknown content (as described in 6.7.2.3) is an incomplete type. (6.2.5.27)

Code⚓︎

第一行能通过:An incomplete type can only be used when the size of an object of that type is not needed. It is not needed, for example, when a typedef name is declared to be a specifier for a structure or union, or when a pointer to or a function returning a structure or union is being declared. (6.2.5.1)

UB19.c
typedef struct s_a A;

int main() {
    A a;
    a;
    return 0;
}

Configurations⚓︎

OS: Microsoft Windows 10 22H2

gcc -v: gcc version 8.1.0 x86_64-w64-mingw32

compile and run commands: gcc -o UB18.exe UB18.c && UB18.exe

OS: arm64-apple-darwin20.6.0

clang -v: Apple clang version 13.0.0 (clang-1300.0.29.30)

compile and run commands: clang -o UB18.out UB18.c && ./UB18.out

Behaviors⚓︎

compile error: storage size of 'a' isn't known

compile error: variable has incomplete type 'A'(aka 'struct s_a')

Note⚓︎

事实上,笔者有经过许多尝试,但并未找到能通过编译的方法。这也就导致样例并未成功运行到object求value阶段(第5行)。

这可能是因为编译器在编译过程中,需要确定object的大小才能分配内存,但对不完全类型,其长度是无法确定的,这就导致无法通过编译。如果读者有合适的样例,或认为本样例有问题欢迎随时提出!