为什么在代码中没有初始化数组的大小时,gcc不会警告? [英] Why doesn't gcc o warn when size of array is uninitialized in this code?
问题描述
好的,所以这是一个我曾经遇到过的错误。这个错误是我用一个未初始化的变量初始化一个数组。早些时候,我使用了一个函数来声明使用某个函数的元素数量,但是在清理之后,我忘记了它,并将所有声明移至了函数的顶部。
I使用标志 -std = c99 -Wall -Wextra -pedantic -O
,并且通常gcc会在未初始化之前使用正在使用的值的警告,但在此特定情况下,吨。所以,我的问题是:
这是 f(& n)
以一种奇怪的方式初始化数组大小?
#include< stdio.h>
void f(int * x){
* x = 8;
}
int main(void){
int n;
float a [n]; //编译器应该警告n可能包含垃圾
a [7] = 3.1415;
printf(%f \ n,a [7]);
f(& n); //删除这会导致编译器按预期发出警告
return 0;
}
编辑:它可能是这个gcc bug ?
GCC接受 float a [n]
作为可变长度数组。但是,它应该警告你,使用它时, n
包含垃圾。也许VLA初始化的重新排列方式使得这个事实对代码生成器不明显?如果 n
在使用前被初始化,将调用移至声明之上的 f()
一个
显然是错误的,但是这个程序产生了未定义的行为。 Okay, so this is a stripped down variant of a bug I had. The bug was that I initialized an array using a variable that wasn't initialized. Earlier I used a function to declare the number of elements using a function, but after a cleanup I forgot about it and moved all declarations to the top of the function.
I used the flags -std=c99 -Wall -Wextra -pedantic -O
, and usually gcc warns about values being used before they are uninitialized, but in this specific case it didn't. So, my question is:
Is this a bug in gcc
or is it possible for f(&n)
to post-initialize the array size in some weird way?
#include <stdio.h>
void f(int * x) {
*x = 8;
}
int main(void) {
int n;
float a[n]; // Compiler should warn that n may contain garbage
a[7] = 3.1415;
printf("%f\n", a[7]);
f(&n); // Removing this causes the compiler warn as expected
return 0;
}
EDIT: It may be this gcc bug?
GCC is accepting float a[n]
as a variable-length array. It should, however, warn you that n
contains garbage when it’s used. Perhaps VLA initialization is getting rearranged in a way that makes that fact non-obvious to the code generator? If n
were initialized before use, moving the call to f()
above the declaration of a
would clearly be wrong, but this program produces undefined behavior.
这篇关于为什么在代码中没有初始化数组的大小时,gcc不会警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!