这是未定义的行为吗
Is this undefined behaviour
#include <stdio.h>
void fun(int *a, int *b) {
//printf("%d %d\n", a[2], *b);
++b; a[2] = a[1] + 6;
return;
}
int main(void) {
char A[5] = {'0', '1', '7', '3', '4'};
fun(A, A[2]);
printf("%c", A[2]);
}
我在这里 读到,使用 int*
访问 char
数组是未定义的行为。这个程序与 link 中的程序相似吗?
此外,我想知道为什么我会收到运行时错误,如果我取消注释函数中的第一条语句 fun
这是 5 种不同的 UB:
是UB,因为编译不过。您不是通过 int*
访问字符数组,而是试图将单个字符转换为 int*
,这是无效的 C。请参阅
同样,您不能将字符数组隐式转换为整数指针。你需要一个明确的转换。
修复代码以便编译,fun((int*)A, (int*)&A[2]);
,然后在函数中:
a[2]
可能导致许多系统上的访问未对齐,这将是 UB。
a[2]
可能是数组越界访问,因为 int
是 32 位。 UB.
a[2] = a[1] + 6;
通过不兼容的类型对数组进行左值访问。这是一个 "strict aliasing violation" 也是 UB。 What is the strict aliasing rule?
#include <stdio.h>
void fun(int *a, int *b) {
//printf("%d %d\n", a[2], *b);
++b; a[2] = a[1] + 6;
return;
}
int main(void) {
char A[5] = {'0', '1', '7', '3', '4'};
fun(A, A[2]);
printf("%c", A[2]);
}
我在这里 int*
访问 char
数组是未定义的行为。这个程序与 link 中的程序相似吗?
此外,我想知道为什么我会收到运行时错误,如果我取消注释函数中的第一条语句 fun
这是 5 种不同的 UB:
是UB,因为编译不过。您不是通过
int*
访问字符数组,而是试图将单个字符转换为int*
,这是无效的 C。请参阅同样,您不能将字符数组隐式转换为整数指针。你需要一个明确的转换。
修复代码以便编译,fun((int*)A, (int*)&A[2]);
,然后在函数中:
a[2]
可能导致许多系统上的访问未对齐,这将是 UB。a[2]
可能是数组越界访问,因为int
是 32 位。 UB.a[2] = a[1] + 6;
通过不兼容的类型对数组进行左值访问。这是一个 "strict aliasing violation" 也是 UB。 What is the strict aliasing rule?