0

I tried to serialize a structure field (int) to a char* buffer but I think I am doing things wrong.

This is what I am using to copy this field.

memcpy(payload + offset, &packet->payload.offset, sizeof(long int));

packet->payload.offset is a long int and contains the value '5' (hardcoded), note that:

If I print: printf("offset: %ld \n", packet->payload.offset); I get: offset: 5

But if I print: printf("offset: %ld \n",&packet->payload.offset), I get: offset: 167120959

If in memcopy I remove the '&' to the second argument to write '5' to the buffer it causes Segmentation Fault, but if I don't, it copies 167120959 (which I supose it is it's address) to the buffer instead of the actual value.

Thank you very much for your help! I tried to be as descriptive as possible, hope you can help me out.

Guillermo Gruschka
  • 167
  • 1
  • 3
  • 16

2 Answers2

2

But if I print: printf("offset: %ld \n",&packet->payload.offset), I get: offset: 167120959

That's because you're printing an address, not a value. Your "serialization" method is OK (endianness aside) because memcpy expects addresses.

I remove the '&' to the second argument to write '5' to the buffer [...] but if I don't, it copies 167120959 (which I supose it is it's address) to the buffer instead of the actual value.

Wrong. It copies sizeof(long int) bytes from that address.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
0
But if I print: printf("offset: %ld \n",&packet->payload.offset), I get: offset: 167120959

That's wrong, it prints the address of packet->payload.offset instead of packet->payload.offset itself.

Memcpy has to be supplied with the address of the variable, else it can't modify it (there's no byref parameter passing in C). So you pass memcpy() the address of the variale, but printf() only needs to read it, so you can (and should) pass the variable directly.