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

假如想象 提交于 2019-12-02 02:49:36

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/33243484/why-doesnt-gcc-o-warn-when-size-of-array-is-uninitialized-in-this-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!