UB15⚓︎
Author: PeiHong Dai
Definition⚓︎
- A program requires the formation of a composite type from a variable length array type whose size is specified by an expression that is not evaluated (6.2.7).
- 程序需要从变长数组类型形成复合类型,而该数组长度由未求值的表达式指定
Description⚓︎
- A composite type can be constructed from two types that are compatible; it is a type that is compatible with both of the two types and satisfies conditions in 6.2.7. Specifically, the undefined situation is clarified below:
- If both types are array types, the following rules are applied:
- If one type is an array of known constant size, the composite type is an array of that size.
- Otherwise, if one type is a variable length array whose size is specified by an expression that is not evaluated, the behavior is undefined.
Code⚓︎
#include <stdio.h>
int m;
int main(void)
{
char arr[m];
m = 3;
printf("%d\n", sizeof(arr));
return 0;
}
Configurations⚓︎
OS: Microsoft Windows 11 22H2
gcc -v : gcc version 7.4.0, x86_64-w64-mingw32
compile and run commands: gcc -o UB15.exe UB15.c && ./UB15.exe
OS: Microsoft Windows 11 22H2
clang -v : clang version 6.0.0, x86_64-w64-mingw32
compile and run commands: clang -o UB15.exe UB15.c && ./UB15.exe
Behaviors⚓︎
Advice⚓︎
-
VLAs in C99 and forth are dependent on other variables, if user interactions are involved during the process, the compiler cannot determine the size during compilation, which could cause UBs.
-
c int n; scanf("%d",&n); int str[n];
-
For better stability and robustness, just try the old-school approach: malloc
-
c int n; scanf("%d", &n); int* str = malloc(n * sizeof(int)); ... free(str);
-
By the way, the sizeof evaluation of VLA is problematic since its implementation is during compilation, our teacher is working on this matter now.