views:

40

answers:

2

Dear all,

I'm not sure if the snippet of C++ code below is legitimate or not:

std::vector<int*> myints;
for (int i = 0; i<N; i++) {
   int j = i;
   myints.push_back(&j);
 }

 for (int i=0; i<myints.size(); i++) cout<<*(myints[i])<<endl;

How does the compiler handle this ? I understand the variable j itself goes out of scope when exiting the for loop but will an integer be locally allocated N times on the stack so that the int objects pointed to by the elements in the vector remain valid outside the loop ?

Many Thanks ! -bert

+1  A: 

Once the block ends, the compiler stops caring about the memory that was previously reserved for them. But even if nothing else disrupts that, you have another problem: all the int*s in the vector<int*> point to the same memory location, so they all have the final value of i.

Ignacio Vazquez-Abrams
Hmm, but when I run this, I get what I'd naively expect, i.e. values of 0, 1, 2, ... are printed. Is this because the compiler unrolls the loop if N is known or somethink like that ?
Bert
I'm wrong. You're right. Thanks.
Bert
A: 

The answer depends (as usual) on compiler's implementation.

You will probably get all pointers pointing to the same location with N's latest value on its pointed direction.

Pablo Santa Cruz
You're right. thanks
Bert