I've discovered that this program continues returning 6 until I start returning 16 or greater instead of 1, at which point the program prints 0. Why? My intention was to use pass the result of a function directly into the static array initialization.
#include <stdio.h>
#include <string.h>
int ret_1() { return 1; }
int main( int argc, const char* argv[] )
{
char arr[ret_1()];
int l = strlen(arr);
printf("The size is: %d\n", l);
return 0;
}
The size is: 6
I wonder if this is undefined behavior generating an arbitrary value, or if there's an underlying issue I'm missing.
Static char array initialization with simple function
This statement
char arr[ret_1()];
defines an array of as much elements as given by ret_1()
, but leaves it uninitialised.
Then this call
int l = strlen(arr);
reads the (uninitialised) array's content/elements and with this invokes undefined behaviour. Anything can happen from this moment on.
To fix this do:
char arr[ret_1()];
memset(arr, 0, sizeof arr); /* Initialise array by (all) zero(s). */
After applying the fix, strlen(arr)
returns 0
, meaning that 0
elements in arr
are used to represent a "string". It stores the equivalent to ""
, the empty string.
This expression sizeof arr
actually returns the number of bytes allocate for arr
, which in your example would be 1
.