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

Where is the "space itself" in the storage allocator described at the end of K&R's book?

在 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;

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

这只是块的 header。也就是说,当分配 space 时,您将分配一定数量的 space,以 sizeof(header) 的倍数分配,将 header 放在第一个 sizeof(header) 字节,然后在分配的内存中剩余 size 字节。从文本(我想;这是我在谷歌上搜索你引用的一些文本时被引导到的,并且出乎意料地来自 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

稍后,在第187,malloc()的示例实现表明,内存总是以header的倍数分配,在开头添加header用于控制信息:

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

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

可能有用的参考资料

这本书讲的是存储分配器。摘录(强调我的):

8.7 Example - A Storage Allocator

[…]

Rather than allocating from a compiled-in fixed-size array, malloc will request space from the operating system as needed. Since other activities in the program may also request space without calling this allocator, the space that malloc manages may not be contiguous. Thus its free storage is kept as a list of free blocks. Each block contains a size, a pointer to the next block, and the space itself.

作者只是指为请求分配的space。假设有 20 KiB 的分配请求,将为该请求创建一个块。它将请求大小作为 int 包含值 20 * 1024 * 1024,后跟指向下一个此类分配块的指针,然后是 20 KiB 的空闲 space(这就是该术语也指)其第一个字节地址被交还给调用者。

在代码后面的页面中显示的是

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

这表明联合仅覆盖 space 的控制信息 (Header) 而不是空闲的 space 本身,后者后来被添加到已分配单元的计数中。