我正在经历这个link并学习 C。页面上有趣的部分:
The real purpose of unions is to prevent memory fragmentation by arranging for a standard size for data in the memory. By having a standard data size we can guarantee that any hole left when dynamically allocated memory is freed will always be reusable by another instance of the same type of union.
我通过下面的代码理解了这部分:
typedef struct{
char name[100];
int age;
int rollno;
}student;
typedef union{
student *studentPtr;
char *text;
}typeUnion;
int
main(int argc, char **argv)
{
typeUnion union1;
//use union1.studentPtr
union1.text="Welcome to StackOverflow";
//use union1.text
return 0;
}
嗯,在上面的代码中,union1.text
是复用了之前union1.studentPtr
使用的空间,虽然没有完全使用,但是还在使用。
现在,我不明白的部分是,什么时候不能使用malloc
释放的空间导致内存碎片?
编辑:浏览评论和答案,必须使用 the classic text , 将此编辑添加到帖子中,假设它会帮助像我这样的初学者
最佳答案
一般而言,评论对 union
有更多专业知识。
具体针对你的问题,我的理解是:
union
为 union 变量中的最大数据类型留出内存。因此,例如在 union 中有一个short int
和一个long int
将为long int
留出足够的内存想象一下,您声明一个
short int
变量而不是 union。 但是这时需要使用一个long int
。所以你在short int
上使用free
然后使用malloc
为long int
分配内存。这必须是连续的内存。所以现在你的内存看起来像这样。 在其他使用的内存块中间有一个空闲字节。坐在那里等着你专门申请 1 字节的内存。
旁白:如果您正在学习c
,我推荐the classic text .它已经过时,但我喜欢它的简单、清晰和教科书风格的方法。
关于c - union如何防止内存碎片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39307629/