natevw
natevw

Reputation: 17903

Do variable length arrays start with default 0 values in C?

I know I cannot initialize variable-length arrays in C with explicitly provided values. The following code is not supported:

void main() {
  int l = 2;
  float test[l] = {1.0, 2.0};  // my compiler says: "Variable-sized object may not be initialized"
}

My question is: if I don't attempt to give any values:

void main() {
  int l = 2;
  float test[l];
}

…will a C compiler make sure it starts initialized to zero by default?

Upvotes: 2

Views: 233

Answers (2)

Eric Postpischil
Eric Postpischil

Reputation: 222354

Variable length arrays are not initialized by default and cannot be initialized explicitly, except that memory allocation routines such as calloc may initialize the space.

C 2018 6.7.6.2 (“Array declarators”) 2 says:

… If an identifier is declared to be an object with static or thread storage duration, it shall not have a variable length array type.

So the storage duration of a variable length array must be one of the other storage durations: automatic or allocated [6.2.4 1]. (There is a temporary storage duration, but only for structures or unions [6.2.4 7].)

6.7.9 10 says objects with automatic storage duration are not initialized by default:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate…

Additionally, 6.7.9 3 says you cannot initialize variable length arrays explicitly:

The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

Upvotes: 3

natevw
natevw

Reputation: 17903

Happy to accept better-documented answers, but empirically the answer is no: the memory is not zero-initialized.

Variants of the following code often (but not always!) abort:

int main() {
  int l = 99;
  float test[l];
  assert(test[0] == 0.0);
  assert(test[42] == 0.0);
  return 0;
}

So unless I'm otherwise sure to initialize every member, it's necessary to get it to a known state myself, e.g.

int main() {
  int l = 99;
  float test[l];
  memset(test, 0, sizeof test);

 // …now the array content is in a known state…
}

I believe that C++ behaves differently which was probably what I was remembering.

Upvotes: 0

Related Questions