C I/O and serialization: If we write the following struct instance with fwrite(), can we read it back with fread() and get the original data reliably across runs and machines?\n\nstruct emp\n{\n char n;\n int age;\n};\nstruct emp e = "CuriousTab", 15; / pointer to string literal */\nFILE *fp;\nfwrite(&e, sizeof(e), 1, fp);

Difficulty: Medium

Correct Answer: No; only the pointer value is written, not the pointed-to string data, so it is not portable or reliable.

Explanation:


Introduction / Context:
This tests understanding of binary serialization in C. Writing a struct that contains pointers using fwrite() does not copy the objects those pointers reference. It only writes the immediate bytes of the struct itself, including raw pointer values that are meaningful only in the original process address space.


Given Data / Assumptions:

  • struct emp has a pointer member `char *n` and an int `age`.
  • We call `fwrite(&e, sizeof(e), 1, fp)` to write the struct bytes.
  • We later call `fread()` expecting to reconstruct the same logical data.


Concept / Approach:
Pointers store addresses, not the data they point to. `fwrite()` writes the pointer value (an address), which becomes meaningless when read back in another process or on another machine. To serialize correctly, either store the string content (e.g., write the characters and length) or redesign the struct to embed a fixed array, or use a proper serialization format.


Step-by-Step Solution:
1) `sizeof(e)` covers the size of `char *` plus `int` and padding. 2) `fwrite()` outputs these raw bytes; the string literal data is not included. 3) On `fread()`, the pointer bytes are read back as an address that is invalid in the new process. 4) Correct pattern: store string contents explicitly (length + bytes) or use `char name[LEN];` in the struct and write that array.


Verification / Alternative check:
If you change process, restart, or move to a different machine or architecture, reading back the raw pointer yields undefined or useless addresses, demonstrating non-portability.


Why Other Options Are Wrong:
Option B: Misunderstands how fwrite works; it does not follow pointers.
Option C/D: Optimization or text mode does not serialize pointed-to data.
Option E: Member order does not solve the fundamental pointer issue.


Common Pitfalls:
Assuming fwrite serializes entire object graphs; ignoring endianness/ABI; forgetting to write string lengths; mixing text and binary I/O improperly.


Final Answer:
No—pointers are not serialized; write the pointed-to data explicitly or avoid pointers.

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion