Reputation: 113
I am new to C++, currently working on a networking project, faced an unusual error with a vector of object pointers.
State class:
struct State
{
public:
int reject_percent_;
int fill_percent_;
int partial_fill_;
bool is_logged_in_;
struct order
{
long id;
long price;
int quantity;
bool is_filled = false;
bool is_partially_filled = false;
};
std::vector<order *> orders;
};
pushing into vector: (here state is an object of State struct)
State::order* o;
o->id = (obj->ClOrdID); // obj->ClOrdID = 1
o->price = (obj->Price); // obj->Price = 1
o->quantity = (obj->OrderQty); // obj->OrderQty = 1
std::cout<<o->id<<"\n"; //outputs 1
state->orders.push_back(o);
in other function:
State::order* ord = NULL;
for (int i = 0; i < state->orders.size(); ++i)
{
std::cout<<((state->orders).at(i)->id)<<"\n"; //outputs :: 93893845689152
std::cout<<((state->orders).at(i)->price)<<"\n"; //outputs :: 93893845689184
std::cout<<((state->orders).at(i)->quantity)<<"\n"; //outputs :: 869246848
if(obj->ClOrdID==(state->orders).at(i)->id)
{
ord=(state->orders).at(i);
break;
}
}
I know this is not a minimal reproducible example, but I think this might be a trivial error that I don't see, the code is big and will take a long time shortening, so please bear with me, can you just point out what might cause this problem, as the values seem to be junk values of the datatypes.
Upvotes: 1
Views: 100
Reputation: 16454
You didn't allocate memory for the order and you didn't initialize the pointer
State::order* o;
Dereferencing this pointer to write into it
o->id = (obj->ClOrdID); // obj->ClOrdID = 1
o->price = (obj->Price); // obj->Price = 1
o->quantity = (obj->OrderQty); // obj->OrderQty = 1
to read from it
std::cout<<o->id<<"\n"; //outputs 1
or copying it
state->orders.push_back(o);
causes undefined behavior. Your program could crash, everything could seem correct or your computer could order a pizza.
It's difficult to say what's the best way to solve this problem with just some code snippets. One way is to change std::vector<order *> orders;
to std::vector<order> orders;
. Another way is to use smart pointers.
Upvotes: 4
Reputation: 238311
State::order* o; o->id = (obj->ClOrdID);
The pointer has an indeterminate value. The behaviour of indirecting through this uninitialised pointer is undefined.
You should probably use this instead:
std::vector<order> orders;
So that the vector contains order instances.
Upvotes: 2