C fread() magically reading dynamically allocated struct members, how?

▼魔方 西西 提交于 2019-12-05 05:08:21

You are writing the data in the struct, which is an int followed by a pointer to a string. It's just data like anything else, and you know how long it is because the struct is fixed length - an int plus a pointer. You read the same pointer to the same name string as the original. The name itself is neither written nor read.

Both person->name and person_read->name wind up pointing to the same memory location. Since you didn't deallocate person->name before reading the file back in, the pointer value in person_read->name is still valid.

If you had deallocated person->name or read the file from a different program, the pointer value would no longer be valid, and attempting to reference it would invoke undefined behavior - you would either have printed out gibberish or gotten a segfault.

The *name pointer remains valid throughout the fwrite and fread calls, which is seemingly a fluke to you. If you free(person->name) before printf you would get the result or error your were expecting.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!