문제

I wrote this code to try and understand a bigger problem in some other larger code, but in the second iteration over the list in main prints garbage and I don't quite get what is going on here. Admittedly I tend to break pointers, but here it looks straight forward to me, anyone have any insight?

std::list<int *> myobjects;
const std::list<int *>& getMYObjects( void );

const std::list<int *>&
getMYObjects( void ) 
{
    return( myobjects );
} 

void fillMYObjects()
{
    int myints[]={15,36,7,17,20,39,4,1};

    for(int i=0;i<8;i++)
    {
        int *temp = &myints[i];
        myobjects.push_back(temp);
        std::cout << "list: " << *temp << std::endl;
        std::cout << "list: " << temp << std::endl;
    }
     std::cout << "listBack: " << *myobjects.back() << std::endl;

   for(std::list<int*>::iterator it=myobjects.begin(); it!=myobjects.end();++it)
   {
        std::cout << ' ' << **it << std::endl;
   } 
}

int main()
{
   fillMYObjects();

   std::list<int*> myobjects2 = getMYObjects();
   for(std::list<int*>::iterator it=myobjects2.begin(); it!=myobjects2.end();++it)
   {
        std::cout << ' ' << **it << std::endl;
   } 
}
도움이 되었습니까?

해결책

The variable myints is a local variable, and will go out of scope once the function returns. What happens to the pointers in the list then? The will point to memory now occupied and overwritten objects.

다른 팁

You are pointing to numbers that are local and thus are on the stack. They are failing out of scope when you leave the function. So you are still pointing to the right address but the data is gone and the addresses are being used for something else.

At the end of the fillMyObject function, the myInts array is destroyed since it was declated inside the function. at the end of this block, at the end of the function, the array do not live anymore, if you want to keep its values, you need to store the value and not the address. they won't be right anymore right after the end ;)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top