I'm experiencing an unexpected interaction with char array initialization.
When initializing a char[] with a size of strlen( char parameter[] ), the newly initialized char[] is too big. I am not sure what is causing this.
int main(void)
{
char myString[] = { " " };
foo( myString );
}
int foo( char str[] )
{
char testString[ strlen( str ) ];
printf( "Length of testString: %lu\n", strlen( testString ) );
return 0;
}
When I run foo, the output is
Length of testString: 6
when I am expecting it to be 1.
Even stranger is when I add a print statement to foo before the initialization of testString, the output seems to magically fix itself:
int foo( char str[] )
{
printf( "Length of str: %lu\n", strlen( str ) );
char testString[ strlen( str ) ];
printf( "Length of testString: %lu\n", strlen( testString ) );
return 0;
}
foo now prints
Length of str: 1
Length of testString: 1
I have a feeling that it has something to do with the way char[] are passed into functions, or perhaps an unexpected behavior of strlen, but I really have no idea.
Any help is appreciated.
testStringarray at all. You specified the size, but the array itself is left uninitialized: it contains garbage. Trying to applystrlento an uninitialized array results in undefined behavior. That's what you are observing. And yes, undefined behavior can and will behave in unpredictable way and might even appear to "magically fix itself".