简体   繁体   English

在堆上分配小于 4KB 的空间?

[英]Allocating less than 4KB on Heap?

Please Notice my followup question under accepted answer.请注意我在已接受答案下的后续问题。

I just read about how translating from virtual to physical memory is done and I got an interesting question.我刚刚阅读了如何完成从虚拟内存到物理内存的转换,我得到了一个有趣的问题。

If the minimum size of frame in physical memory is 4KB why doesn't that say we can use heap for a minimum allocation of 4KB?如果物理内存中的最小帧大小是 4KB,那为什么不说我们可以使用堆来分配最小 4KB 的空间? Or that if I wanted only 1 byte on heap then it allocates the whole frame of 4KB and the rest is kept unused (even that there is space for others) Or It's split with other allocations/process since we have the offset field?或者,如果我只想要堆上的 1 个字节,那么它会分配整个 4KB 帧,其余部分保持未使用状态(即使有其他空间供其他人使用)或者它与其他分配/进程分开,因为我们有偏移字段?

Try this code:试试这个代码:

int main()
{
    int* a = malloc(sizeof *a);
    int* b = malloc(sizeof *b);
    printf("%p\n", (void*)a);
    printf("%p\n", (void*)b);
    return 0;
}

Possible output:可能的输出:

0x2164010
0x2164030

As you can see the allocated memory is within the same 4KB page (0x2164xxx), it has a 16-byte offset from the page and a 16-byte alignment).正如您所看到的,分配的内存在同一个 4KB 页面(0x2164xxx)内,它与页面有 16 字节的偏移量和 16 字节的对齐方式)。

Even if the mapping from physical to virtual addresses is done on some page size (eg 4KB), there may be several dynamic allocations within one mapped page.即使从物理地址到虚拟地址的映射是在某个页面大小(例如 4KB)上完成的,在一个映射页面内也可能有多个动态分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM