Incorrect data when passing pointer a list of pointers to a function. (C++)
Posted
by
Phil Elm
on Stack Overflow
See other posts from Stack Overflow
or by Phil Elm
Published on 2011-11-28T01:30:43Z
Indexed on
2011/11/28
1:49 UTC
Read the original article
Hit count: 106
I'm writing code for combining data received over multiple sources. When the objects received (I'll call them MyPacket for now), they are stored in a standard list.
However, whenever I reference the payload size of a partial MyPacket, the value shows up as 1 instead of the intended size.
Here's the function code:
MyPacket* CombinePackets(std::list<MyPacket*>* packets, uint8* current_packet){
uint32 total_payload_size = 0;
if(packets->size() <= 0) return NULL; //For now.
std::list<MyPacket*>::iterator it = packets->begin();
//Some minor code here, not relevant to the problem.
for(uint8 index = 0; index < packets->size(); index++){
//(*it)->GetPayloadSize() returns 1 when it should show 1024. I've tried directly accessing the variable and more, but I just can't get it to work.
total_payload_size += (*it)->GetPayloadSize();
cout << "Adding to total payload size value: " << (*it)->GetPayloadSize() << endl;
std::advance(it,1);
}
MyPacket* packet = new MyPacket();
//Byte is just a typedef'd unsigned char.
packet->payload = (byte) calloc(total_payload_size, sizeof(byte));
packet->payload_size = total_payload_size;
it = packets->begin(); //Go back to the beginning again.
uint32 big_payload_index = 0;
for(uint8 index = 0; index < packets->size(); index++){
if(current_packet != NULL) *current_packet = index;
for(uint32 payload_index = 0; payload_index < (*it)->GetPayloadSize(); payload_index++){
packet->payload[big_payload_index] = (*it)->payload[payload_index];
big_payload_index++;
}
std::advance(it,1);
}
return packet;
}
//Calling code
std::list<MyPacket*> received = std::list<MyPacket*>();
//The code that fills it is here.
std::list<MyPacket*>::iterator it = received.begin();
cout << (*it)->GetPayloadSize() << endl; // Outputs 1024 correctly!
MyPacket* final = CombinePackets(&received,NULL);
cout << final->GetPayloadSize() << endl; //Outputs 181, which happens to be the number of elements in the received list.
So, as you can see above, when I reference (*it)->GetPayloadSize(), it returns 1 instead of the intended 1024.
Can anyone see the problem and if so, do you have an idea on how to fix this? I've spent 4 hours searching and trying new solutions, but they all keep returning 1...
EDIT:
© Stack Overflow or respective owner