Here in this code the function "foo" adds local objects to a global list.
Then the function "bar" tries to access the list. In this simple example it worked.
(I was expecting some garbage values or other errors like invalid memory access).
So to ensure that "foo"'s stack values are destroyed, I made a large array of doubles
(which I later changed to smaller and smaller, and ultimately to 1)
in "bar". And now I get invalid values from the list and mem errors too.
I was expecting this to happen. Because the objects were created on stack so they were
gone!
Now is there a better way to do the same i.e. :
the "foo" function will create new objects
and the "bar" function will access them.
There is only way on my mind right now i.e. to create objects using "new".
Help Please!
Code:
#include <iostream>
#include <string>
#include <list>
#include <cmath>
using namespace std;
typedef list<string> mylist;
mylist msg_list;
void foo()
{
string h("Hello");
string w("World");
msg_list.push_back(h);
msg_list.push_back(w);
}
void bar()
{
double vals[1024];
for (int i=0; i<sizeof(vals)/sizeof(double); ++i)
{
vals[i] = i * sin(3.1415/180.0 * i);
}
mylist::const_iterator it = msg_list.begin();
while (it != msg_list.end())
{
cout << "Msg: " << *it << endl;
++it;
}
}
int main()
{
foo();
bar();
return 0;
}