Skip to content

UB18⚓︎

Author: Kai Xu

Definition⚓︎

An lvalue does not designate an object when evaluated (6.3.2.1).

左值在evaluate时没有指定对象

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)"

The definition of evaluate can't be found in the standard. From my opinion, evaluate is the process of extracting value from an object

标准中并没有对evaluate的定义。笔者认为,evaluate是在object中提取value的过程

Code⚓︎

The 4th line of the code declares the variable p, where p, as the identifier, is lvalue. Variable p is allocated memory space (automatic storage duration) during declaration, which corresponds to an object.

At the same time, *p can point to a block of memory (an object), which is also a lvalue. But the memory (object) pointed to was not allocated. If the 4th line is int *p = 0;, *p will point to an object.

代码第4行声明了变量p,此时p作为identifier是lvalue;p在声明时分配了内存空间(automatic storage duration),也就对应一个object。

同时,*p能够指向一块内存(一个object),也是lvalue。但并没有分配指向的内存(object)。如果第4行为int *p = 0;,那么便指向了object。

UB18.c
#include "stdio.h"

int main() {
    int *p;
    printf("*p = %d", *p);
    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⚓︎

runtime error: 退出代码-1073741819 (0xC0000005)

segmentation fault ./UB18.out

Advice⚓︎

出现UB18对代码是极不负责的,这有可能带来极大的危害。大多数现代编译器对此也直接报错。