复制结构的内容在临时结构为 `free` d 后发生变化

标签 c struct binary-tree

我正在制作一个简单的数据库程序来学习结构和二叉树。我创建了一个包含 3 个字段的全局结构 Student:名字、姓氏、年龄,并编写了一个函数来获取 3 个用户输入(存储为字符串 in_fnamein_sname 和 int in_age,比方说)并将它们放入临时结构 new 中,并计划将它们复制到主树的适当位置.在获取第一个条目的用户输入后,我有:

struct Student *new;
new = (Student *) malloc (sizeof(struct Student));
strcpy (new->fname, in_fname);
strcpy (new->sname, in_sname);
new->age = in_age;
new->left = new->right = NULL;
printf("Contents of new is '%s', '%s', '%d'.\n",new->fname, new->sname, new->age);

student_tree = new  /* wanting to copy the new student as the first entry in the tree*/

现在当我

print("Contents of structure is '%s', '%s', '%d'.\n",student_tree->fname, student_tree->sname, student_tree->age);

我得到了正确的条目,表明复制成功了,但是当我

free(new)
print("Contents of structure is '%s', '%s', '%d'.\n",student_tree->fname, student_tree->sname, student_tree->age);

(认为它是临时的,我不再需要它了)当我第一个条目 fname 总是损坏,包含垃圾。

有人可以解释我错过了什么吗?不一定要固定的代码,只是想了解为什么当我从中复制的东西消失时树中结构的内容会发生变化,以及如何永久复制它。

非常感谢,

W

最佳答案

因为student_treenew是指针。当你将new赋值给student_tree时,没有复制,它只是让student_tree指向同一个内存。当你调用free(new)时,它会回收new指向的内存,也就是student_tree指向的内存,所以可以理解垃圾。

下面是一些将执行实际复制的代码:

struct Student* student_tree = malloc(sizeof(struct Student));
*student_tree = *new;

这里我创建了指针student_tree,分配内存来存放struct Student,最后将new指向的内存中的内容放入code>在student_tree指向的内存中。

关于复制结构的内容在临时结构为 `free` d 后发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50090878/

相关文章:

c - 使用 C 将文件内容分配给变量?

c - 添加第一个学生的记录后它停止工作并且不会将数据保存在文件中

c - 在 C 中为二叉树实现 'insert' 函数

python - 二叉树递归循环返回 None

language-agnostic - 使用 HashMap 将二叉树插入优化为 O(1) 以写入重树

c - 将c头文件翻译为delphi 2006

c - 链接到 Cmake 中不存在的共享库

c - 如何在 SSE/AVX 中使用融合乘加 (FMA) 指令

c - 结构效率

c++ - 如何在 C++ 中调用泛型结构