2

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
  • 1
    looks like a bug to me Commented Oct 20, 2015 at 18:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How do you mean? I it's unclear; removing f(&n) from main causes the compiler to catch and warn that n is used uninitialized.
Yes, that definitely sounds like a compiler bug. Suppose you’d initialized int n = 1; float a[n]; f(&n);. In that case, the compiler clearly needs to update n after it allocates the VLA. Some refactoring during the optimization phase is confusing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.