Ask coding questions

← Back to all posts
Why does my serialization of a C struct fail?

Hello fellow replers,

For a small experiment of my own, I've tried to serialize a C structure called Point2D, which stores two signed integers x and y, into a file. Then, I wanted to read that data from a file into another Point2D struct.

The original is named data1. It's x and y members are set to 12 and 24 respectively. The copy to store the serialized data is named copy. It should have the same values as data1.

Code's Goal:
To achieve this, I've made 2 functions called Point2D_Serialize and Point2D_Load. The first one is supposed to write a Point2D struct from its pointer into a file as bytes (chars). The second one is supposed to read the serialized character bytes of the previous Point2D struct's data into a dynamically allocated Point2D pointer.

Also, I've put various checks for null pointers and open file failures. I don't think that those are causing problems.

Actual Code Behavior:
However, when I ran my code a few times, copy always ends up with copy.x = 0 and copy.y = 0. I suspect that my Point2D_Read() function is bugged, but I don't understand why it's not reading the values correctly.

I'd like some help from anyone who happens to stop by, thanks!