When I run the following C++ code from CodeBlocks on Windows using the mingw compiler, all is fine. But, when I run it on Mac OS X it doesn’t work:
void func (vector<int> &v1, vector<vector< int *> > &v2);
int main()
{
vector<int> v1;
v1.push_back(0);
vector<vector <int *> > v2;
vector<int *> vTemp;
int x = 0;
int * ptr = &x;
vTemp.push_back(ptr);
v2.push_back(vTemp);
func(v1,v2);
cout<<*(v2[0][1])<<endl;
return 0;
}
void func (vector<int> &v1, vector<vector< int *> > &v2)
{
v1.push_back(1);
int *ptr = &(v1[1]);
v2[0].push_back(ptr);
cout<<*(v2[0][1])<<endl;
v1.push_back(2);
int *ptr2 = &(v1[2]);
v2[0].push_back(ptr2);
v1.push_back(3);
int *ptr3 = &(v1[3]);
v2[0].push_back(ptr3);
}
The output I expect (and get on Windows) is
1
1
But on the Mac, I get
1
0
Does anyone have any idea why this should be happening?
Your program is invalid, and you’re seeing undefined behavior. Your pointer value holds the address of a vector element which may be invalid after the
vectorresizes.Running the program with GuardMalloc enabled catches this for you.