c - K&R 书末描述的存储分配器中的 "space itself"在哪里?

标签 c memory-management kernighan-and-ritchie

在 Kernighan 和 Ritchie 的书 The C Programming Language 的最后,描述了一个存储分配器。它说

Each block contains a size, a pointer to the next block, and the space itself.

但是我在代码中没有看到:

typedef long Align;  /* for alignment to long boundary */

union header {       /* block header */
   struct {
      union header *ptr; /* next block if on free list */
      unsigned size;     /* size of this block */
   } s;
   Align x;          /* force alignment of blocks */
};

typedef union header Header;

指向下一个 block 的指针是*ptr,大小是unsigned size,但空间本身是哪个变量?空格本身就是变量x吗?

最佳答案

那只是 block 的标题。也就是说,当分配空间时,您将分配一定数量的空间,以 sizeof(header) 的倍数为单位,将 header 放在第一个 sizeof(header) 字节中,然后在分配的内存中保留 size 字节。从文本(我认为;这是我在 Google 上搜索您引用的一些文本时得到的结果,意外地来自 Java 教程站点),重点补充说:

A free block contains a pointer to the next block in the chain, a record of the size of the block, and then the free space itself; the control information at the beginning is called the "header." To simplify alignment, all blocks are multiples of the header size, and the header is aligned properly. This is achieved by a union that contains the desired header structure and an instance of the most restrictive alignment type, which we have arbitrarily made a long[.]

page 186, Chapter 8, The C Programming Language, Second Edition

稍后,在 p. 187,ma​​lloc()的示例实现表明,内存总是以多个header的倍数分配,并在开头添加一个header用于控制信息:

void *malloc(unsigned nbytes)
{
    /* ... */
    nunits = (nbytes+sizeof(Header)-1)/sizeof(Header) + 1;

page 187, Chapter 8, The C Programming Language, Second Edition

可能有用的引用资料

关于c - K&R 书末描述的存储分配器中的 "space itself"在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32586876/

相关文章:

c - 如何判断进程是否是第一次启动

Python C API : when are we at the end of a Python instruction?

iphone - iOS内存警告tableView EXC_BAD_ACCESS在多 View 应用程序中崩溃

c - K&R 书本练习 4-2

c - 什么是 ubuntu 中的 EOF 以及 Kernighan 和 Ritchie

c++ - 使用对讲机进行远程内存访问

c - 在另一个结构中向前声明的结构数组

c# - 具有引用成员的结构 : heap or stack?

objective-c - NSAutoreleasePool 自动释放池是如何工作的?

c - getchar 是否定义为宏?