简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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