如果 malloc() 在每个系统上分配或不分配连续内存,请用引用澄清

Clarifying with references if malloc() allocates or not contiguous memory on every system

在 K&R 书的第 8 章中,解释了 malloc() 如何在空闲内存中创建一个块列表,每个块都指向下一个(粗略地说) ,不需要连续。 另一方面,每个人都声称 malloc() 以连续的方式分配内存,我看到指针算法被大量使用,类似的问题在这个网站上。 但是,总是没有任何官方来源

我阅读了 C 参考资料,发现没有提到连续性,我发现最好的是在 Linux 和 Windows 手册页上,他们确保 属性 他们的 系统。

因此:malloc() 是否仅在规范的现代系统上提供连续内存(例如使 then 指针算术合法),或者它是否是由 > C89 标准管理的规则,我天真地忽略了哪些?请提供官方参考。谢谢。

Ps:这不仅仅是一个理论问题。我正在为旧的 DOS 系统编写一些代码,我需要确定 malloc.

的正确用法

编辑:我现在明白我的错误了,谢谢。也就是说,我仍然没有找到官方资源,其中明确指出单个 malloc() 调用 returns 连续内存(为什么这个信息不是简单地包含在功能描述下方,在标准库中......?)例如,这里没有痕迹(https://en.cppreference.com/w/c/memory/malloc)。

引用的意思是,如果您多次调用 malloc,则分配的块不必相邻。

但是在每次调用 malloc 时,它都会分配相邻字节的单个内存范围。如果它不能这样做,它 returns 一个空指针。

来自 C 标准(7.22.3 内存管理函数)

1 The order and contiguity of storage allocated by successive calls to the aligned_alloc, calloc, malloc, and realloc functions is unspecified. The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated)...

我想我可以引用本书相关的段落:

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. The blocks are kept in order of increasing storage address, and the last block (highest address) points to the first.

你误会了,它说每次malloc连续调用不一定都是连续分配的space。这并不意味着一个分配的区块不是连续的。而且,事实上,今天 OS 和现代 CPU 游戏中还有一个 MMU,我建议您阅读一下。