Why do I get different results from C code running in gcc and Visual Studio running it

Advertisements
#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 :

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.

Leave a ReplyCancel reply