Recently I tried to implement a simple algorithm in C++ using containers and I ran into a behavior I did not expect and I can not explain. I am new to work with containers so it is possible that the explanation is simple but I just can not see it now.
So, I have a structure to represent a Point that is as simple as:
struct Point{
double x;
double y;
double z;
};
and a simple function for its printing
ostream& operator<<(ostream & os, const Point p){
os << "x= "<<p.x << " y= "<<p.y << " z= "<<p.z;
return os;
}
Now, in a certain part of the code, I allocate a vector of Points of certain size and fill it.
vector<Point>* points = new vector<Point>(number_of_lines);
for (int i = 0; i < number_of_lines; i++){
(*points)[i] = some_data;
}
Later in the code I call
Point* new_point = function_g(points);
cout<<"Outside the function1 : " << *new_point<<endl;
cout<<"Outside the function2 : " << *new_point<<endl;
where the function_g
is defined (somewhat) as:
Point* function_g(vector<Point>* points){
Point* out;
int len = points->size();
for(int j = 0; j<len; j++){
Point i = points->at(j);
if (some_condition){
out = &i;
}
}
cout << "In the function: " << *out<<endl;
return out;
}
So in this function_g
I intend to iterate over the points and find one that fits a condition (I know there is one there) and then I want to return a pointer to the point so I can work with it further in the code. However, when I run the code, I get:
In the function: x= 0.1 y= 0.1 z= 0.1
Outside the function: x= 0.1 y= -8.69944e+32 z= 0.1
Outside the function: x= 4.67894e-310 y= -8.69944e+32 z= 4.94066e-324
so in the function, I get right results when using the pointer, however outside they go wrong and the pointed memory is corrupted. Can anyone explain me, please, what is happening?