gpt4 book ai didi

c++ - malloc() 用于跟踪分配大小的空间

转载 作者:太空狗 更新时间:2023-10-29 20:55:11 34 4
gpt4 key购买 nike

malloc() 函数会在返回点之前的 8 个字节(在 64 位系统中)放置一些信息,一些关于缓冲区大小的信息。但是有一些差异比我预期的要大。

char *p = (char*)malloc(0x12345678);

前8个字节显示数字0x12346002

(gdb) x/32ubx p-8
0x7fffe56cf008: 0x02 0x60 0x34 0x12 0x00 0x00 0x00 0x00
0x7fffe56cf010: 0x68 0x65 0x6c 0x6c 0x6f 0x20 0x77 0x6f
0x7fffe56cf018: 0x72 0x6c 0x64 0x0a 0x00 0x00 0x00 0x00
0x7fffe56cf020: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00

为什么会有这么大的差异

最佳答案

malloc() function will put some info in the 8 bytes (in 64bit system) before the returned point some info about the size of the buffer.

虽然这是实现内存管理例程的一种非常常见的方式,但它并不通用;例如,图书馆可以保留一个单独的哈希表来跟踪分配大小。该标准允许图书馆选择他们喜欢的实现方法。

the 8 bytes before it shows the number 0x12346002

假装进入分配地址之前的 8 个字节不是未定义的行为(实际上是)。为了优化潜在的 realloc,库被允许在他们认为合适的时候四舍五入。在这种情况下,库决定额外分配 2442 个字节,以防您稍后决定重新分配

Wonder why there is such a big difference

虽然 2442 的绝对数量很多,但相对于分配的总体规模而言,这是一个很小的数目。

关于c++ - malloc() 用于跟踪分配大小的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36521486/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com