c - union如何防止内存碎片?

标签 c memory

我正在经历这个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 留出足够的内存 2 bytes set aside for long int

  • 想象一下,您声明一个 short int 变量而不是 union。 1 byte for small int 但是这时需要使用一个long int。所以你在 short int freeing small int memory 上使用 free 然后使用 malloclong int 分配内存。这必须是连续的内存。所以现在你的内存看起来像这样。 enter image description here在其他使用的内存块中间有一个空闲字节。坐在那里等着你专门申请 1 字节的内存。

旁白:如果您正在学习c,我推荐the classic text .它已经过时,但我喜欢它的简单、清晰和教科书风格的方法。

关于c - union如何防止内存碎片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39307629/

相关文章:

c - 放置内核启动前已知且从未更改的常量内存的最佳位置

c - 函数局部范围内变量的重复标识符

c - 如何从包含字符和整数的文本文件中读取整数?

用于传递参数的连续内存

qt - 制作轻量级网络浏览器 - Gecko vs Webkit vs ???; Qt4 vs Qt5 vs?

c - C 中 free() 的确切输出?

c - C 的评分点

iOS AssetLibrary 存储指针

memory - Rust - 为什么 malloc/alloc 和更多 'idiomatic' 方法之间的内存使用差异如此之大

C如何释放子内存?