UB39⚓︎
Author: Kai Xu
Definition⚓︎
The operand of the unary * operator has an invalid value (6.5.3.2).
一元*
运算符的操作数是无效值
Description⚓︎
The standard provides three examples:
- a null pointer
- an address inappropriately aligned for the type of object pointed to
- the address of an object after the end of its lifetime
标准给出了三个示例:
- 空指针
- 指针没有和指向对象类型对齐
- 指向对象结束生命周期
Code⚓︎
#include "stdio.h"
#include "stdlib.h"
void test_example_1() {
int *p1;
printf("p1 = %p\n", p1);
printf("*p1 = %d\n", *p1);
}
void test_example_2() {
int a;
int *p2 = (int*)((char*)&a + 1);
printf("&a = 0x%p\n", &a);
printf("p2 = %p\n", p2);
printf("*p2 = %d\n", *p2);
}
void test_example_3() {
int *p3 = (int*) malloc(4);
printf("p3 = %p\n", p3);
free(p3);
printf("*p3 = %d\n", *p3);
}
int main() {
test_example_1();
// test_example_2();
// test_example_3();
}
Configurations⚓︎
OS: Microsoft Windows 10 22H2
gcc -v: gcc version 8.1.0 x86_64-w64-mingw32
compile and run commands: gcc -o UB39.exe UB39.c && UB39.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 UB39.out UB39.c && ./UB39.out
Behaviors⚓︎
test_example_1: p1 = 0x0000000100000000 进程已结束,退出代码-1073741819 (0xC0000005)
test_example_2: &a = 0x00000035b21ff9f4 p2 = 0x00000035b21ff9f5 *p2 = -184549249
test_example_3: p3 = 0x0000020f1c5e5df0 *p3 = 475922768
test_example_1: p1 = 0x0 zsh: segmentation fault ./UB39.out
test_example_2: &a = 0x0x16dc3b40c p2 = 0x16dc3b40d *p2 = 536870912
test_example_3: p3 = 0x1346067f0 *p3 = 0
Advice⚓︎
UB39是绝对不应该出现在程序的