Are variables in array sizes allowed in C?

115 Views Asked by At

I'm using the GCC compiler on Linux. I don't understand how variables work in array sizes.

When I run:

char string[6];
string[0] = 'h';
printf("%s", string);

As expected, it outputs: h

If I run:

int x = 1;
char string[5 + x];
string[0] = 'h';
printf("%s", string);

it outputs h followed by � and other random characters. I guess it's accessing memory addresses, it's not supposed to. The characters are different every time, it's run.

When I do the same but replace line two with "char string[5 + x] = {}" It errors: variable-sized object may not be initialized.

If I do the same with an integer array, it works perfectly fine if I type "int array[5 + x] = {};" but not "int array[5 + x]"

Are variables allowed in the size declarations of int arrays, but not in char arrays/strings?

2

There are 2 best solutions below

1
Chris On

As noted in comments, your problem is that the below invokes undefined behavior.

int x = 1;
char string[5 + x];
string[0] = 'h';
printf("%s", string);

The undefined behaviour stems from using string as a string. Strings in C require a null terminating character to signal the end of the string. Your variable length array has not been initialized (apart from the first character) so the contents are indeterminate. You have a 5 + x sized chunk of memory, but that memory could be in any state.

In the first case, string[1] was clearly 0, thus null-terminating the string. This is not guaranteed as you can see from the second example where printf printed gibberish because it didn't see the next character after 'h' being a null terminator.

With a static-sized array we would initialize it with {0} or {} to set the contents to zero, but VLAs may not be initialized this way.

3
chux - Reinstate Monica On

To address the titled part of OP's concern:

Are variables in array sizes allowed in C?

Before C99: Variable length arrays (VLA) are not standard.

C99: Standard

C11, C17: If __STDC_NO_VLA__ is defined, then no VLA support.
otherwise VLAs are supported.

C23: (At least how it is currently proposed.) Like C11, C17. "usage of VLA type is allowed except creating VLA object with automatic duration ... which is optional." per __STDC_NO_VLA__. @tstanisl


Are variables allowed in the size declarations of int arrays, but not in char arrays/strings?

If allowed for one type, VLA allowed for all array types.


printf("%s", string); is bad code as "%s" expect a pointer to a string. string is not a string as it does not certainly contains a null character. Result: Undefined behavior (UB).