Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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();
}

enter image description here

enter image description here

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading