Find the Error: Pointers, Structures, and Files

This month’s Exercise was originally how to create a structure pointer, fill it with data, and write that data to a file. It’s a procedure fraught with traps and peril. What’s even more challenging is when you’re presented with this type of code and it doesn’t work, but it’s your job to fix it.

I’ve spent my share of time debugging someone else’s work. It’s maddening! That’s because you eventually get your own style and preferences, but soon you discover that other programmers lack such discipline.

Even when reviewing my own code, I often get frustrated with myself for not documenting the process in a better way. I could go on . . . but instead, I present this month’s Exercise, which is based on code a reader asked me to debug.

The code creates a pointer to a structure. Memory is allocated for the structure and the members are assigned values. Then the structure is written to a file, read back from the file, then the contents displayed. The code compiles, which doesn’t help you debug. Further, it appears as though the program works flawlessly — but it doesn’t!

Click here to view the code.

Here is the sample output:

File created!
Data saved!
File opened!
Word: alpha
Value: 1

According to the output, the program runs great. Values alpha and 1 are written to the file and apparently read back in. But here is the hexdump of the file’s contents:

00000000  50 27 40 e5 d6 7f 00 00                           |P'@.....|
00000008

As you can see, the word alpha doesn’t appear in the file. So something has gone awry. Your job is to figure out what.

Please attempt to solve this problem on your own. Click here to read how I solved the problem and what’s specifically wrong with the code.

Leave a Reply