Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming with global variables giving wrong results

Tags:

c++

I've been coding for a while in other languages and am pretty proficient, but now I am diving more deeply into C++ and have come across some weird problems that I never had in other languages. The most frustrating one, which a google search hasn't been able to answer, is with two different code orders.

The background is that I have an array of integers, and a pointer an element in the array. When I go to print the pointer one method prints correctly, and the other prints nonsense.

An example of the first code order is:

#include <iostream>

using namespace std;

void main(){
    int *pAry;
    int Ary[5]={2,5,2,6,8};

    pAry=&Ary[3];

    cout<<*pAry<<endl;

    system("pause");
}

and it works as expected. However this simple order wont work for the full project as I want other modules to access pAry, so I thought a global define should work, since it works in other languages. Here is the example:

#include <iostream>

using namespace std;
int *pAry;
void evaluate();

void main(){

    evaluate();
    cout<<*pAry<<endl;

    system("pause");
}

void evaluate(){
    int Ary[5]={2,5,2,6,8};
    pAry=&Ary[3];
}

When I use this second method the output is nonsense. Specifically 1241908....when the answer should be 6.

First I would like to know why my global method isn't working, and secondly I would like to know how to make it work. Thanks

like image 505
sleepingawake86 Avatar asked Dec 05 '22 07:12

sleepingawake86


2 Answers

In the second example, Ary is local to the function evaluate. When evaluate returns, Ary goes out of scope, and accessing it's memory region results in undefined behaviour.

To avoid this, declare Ary in a scope where it will still be valid at the time you try to access it.

like image 88
JBentley Avatar answered Dec 09 '22 14:12

JBentley


It's not working because your pAry is pointing into a local array, which is destroyed when you return from evaluate(). That's undefined behavior.

One possible fix is to make your local array static:

static int Ary[5]={2,5,2,6,8};
like image 40
Fred Larson Avatar answered Dec 09 '22 15:12

Fred Larson