Why do I get different results from C code running in gcc and Visual Studio running it
#include <stdio.h>
int A()
{
int array[10];
int i;
for (int i = 0; i < 10; i++)
{
array[i] = i;
}
}
int B()
{
int array[10];
int i;
for (int i = 0; i < 10; i++)
{
printf("%d", array[i]);
}
}
int main()
{
A();
B();
}
This is my code, I think array should be re-initialized once in function B, so I think Visual Studio's answer is what I want, but I can't understand why GCC is returning this answer
Solution 1:
For starters in the both functions the variable i
declared after the array declaration
int array[10];
int i;
is not used.
The code has undefined behavior because you are trying to output an uninitialized local array in the function B.
Also the functions return nothing though their return type ins not void
.
int B()
{
int array[10];
int i;
for (int i = 0; i < 10; i++)
{
printf("%d", array[i]);
}
}
What you need is the following
#include <stdio.h>
void A( int array[], int n )
{
for ( int i = 0; i < n; i++)
{
array[i] = i;
}
}
void B( const int array[], int n )
{
for (int i = 0; i < n; i++)
{
printf("%d ", array[i]);
}
putchar( '\n' );
}
int main( void )
{
enum { N = 10 };
int array[N];
A( array, N );
B( array, N );
}
Solution 2:
You allocate memory for your array in A()
, which is then initialized.
Usually local variables are allocated on the stack.
After returning from function A()
the stack is cleaned up.
Then B()
is called and the return address is pushed onto the stack. B()
will probably push rbp in order to correct the stack frame and then allocates memory on the stack for the array that happens to be similar to the array used in A()
. Since no-one took the trouble to initialize the memory, it will still contain the same values as before. But that should be considered a coincidence.
Different compilers will use different ways of managing memory. Furthermore Windows uses another calling convention than Linux. All factors that could explain differences.
The main problem is that you are using uninitialized memory and that can lead to virtually anything.