简体   繁体   English

在此代码中未初始化数组大小时,为什么gcc o不发出警告?

[英]Why doesn't gcc o warn when size of array is uninitialized in this code?

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. 我使用了标志-std=c99 -Wall -Wextra -pedantic -O ,并且通常gcc在未初始化值之前就警告它们正在使用的值,但是在这种情况下,它没有使用。 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? 这是gcc的错误, 还是 f(&n)以某种奇怪的方式后初始化数组大小?

#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错误

GCC is accepting float a[n] as a variable-length array. GCC接受float a[n]作为可变长度数组。 It should, however, warn you that n contains garbage when it's used. 但是,它应该警告您n在使用时包含垃圾。 Perhaps VLA initialization is getting rearranged in a way that makes that fact non-obvious to the code generator? 也许VLA初始化正在以某种方式重新排列,使得该事实对于代码生成器而言不是显而易见的? 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. 如果n在使用前进行初始化,移动电话,以f()的声明,上面a显然是错误的,但这个方案将产生不确定的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM