Struct has different size after passing to func

I created a structure with a variable Id and a list of values. When I check the size before passing it to the function as void * it is 12. Once it gets into the function it is 4. How to keep the size the same?

Structure code:

typedef struct
{
    int id;
    std::list<int> sensorValues;
}dataPacketDef;

      

Sending another function code:

  void SendDataBufferToServer()
{
    cout << "Sending network data size: " << sizeof(dpd) << "\n";
    client.writeData((void*)&dpd);
}

      

In the above function, the size is 12, but in the receive function, the size is only 4. The structure is declared as a global variable for my main program.

+3


source to share


5 answers


The pointer size is 4 bytes (or 8 if you are using the x64 compiler). If one writeData

needs to know the size of the object pointed to by the object, this information must be conveyed to it in some way; a common idiom is to pass the size as the second argument. With this, you can use the helper function template to keep things simple:

template<typename T>
void writeData(Client& client, const T& obj)
{
   client.writeData((void*)&obj, sizeof(obj));
}

      



Even though plainly noted in the comments of the question, client.writeData()

it probably still won't be able to accomplish what you want due to the presence list

in dataPacketDef

.

+2


source


before passing it to the function as void *, it is 12. Once it enters the function, it is 4

Since the sizeof pointer in the case of your program is 4 bytes, you cannot read the sizeof struct if you cast your struct instance to void *. You can fix this by passing your function and the size of your structure, i.e. foo(static_cast<void*>(&myStructObj), sizeof(TypeOfMyStruct))

...



[edit]

as well as in Lightning Races in Orbit mentioned in his answer, std :: list serialization is wrong, you will only write pointers to your file /

+3


source


In the function, you take the size void*

, not the dataPacketDef

. And apparently sizeof(void*)

there are 4 bytes on your system . The operator sizeof

is type-only: it does not perform magic pointer checking. In fact, since you've done style erase with this legacy app, it can't.

You cannot serialize your object this way. The list is not flat data; its elements are not actually part of it dataPacketDef

, but dynamically allocated. The list contains pointers to these items. All you do is serialize pointers, which immediately becomes meaningless on the target system.

Ditch this approach entirely and see how to properly serialize objects in modern C ++.

+3


source


It is right.

A pointer always contains an address, which on your computer is 4 bytes.

Therefore, the size of any pointer will be 4 bytes in a 32-bit addressing architecture.

0


source


sizeof (void *) is 4 bytes on a 32 bit machine.

0


source







All Articles