为什么分配单个字节时地址不连续? [英] Why are address are not consecutive when allocating single bytes?

查看:121
本文介绍了为什么分配单个字节时地址不连续?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在动态分配内存,如下所示:

I am dynamically allocating memory as follows:

char* heap_start1 = (char*) malloc(1);
char* heap_start2 = (char*) malloc(1);

当我按如下方式执行printf时,这些地址不是连续的.

When I do printf as follows surprisingly the addresses are not consecutives.

printf("%p, %p \n",heap_start1,heap_start2);

结果:

   0x8246008, 0x8246018

如您所见,磁盘碎片整理保留了15个字节的额外内存.绝对不是因为单词对齐.奇怪的对齐背后有什么想法吗?

As you can see there is a 15 bytes of extra memory that are left defragmented. It's definitely not because of word alignment. Any idea behind this peculiar alignment?

提前谢谢!

如果这很重要,我正在Linux中使用gcc.

I am using gcc in linux if that matters.

推荐答案

glibc的malloc,对于小于16字节的小内存分配,只需将内存分配为16字节即可.这是为了防止在释放此内存时出现外部碎片,在这种情况下,空闲内存的块太小而无法在一般情况下用来执行新的malloc操作.

glibc's malloc, for small memory allocations less than 16 bytes, simply allocates the memory as 16 bytes. This is to prevent external fragmentation upon the freeing of this memory, where blocks of free memory are too small to be used in the general case to fulfill new malloc operations.

malloc分配的块还必须足够大,以将跟踪它所需的数据存储在存储空闲块的数据结构中.

A block allocated by malloc must also be large enough to store the data required to track it in the data structure which stores free blocks.

此行为在增加内部碎片的同时,减少了整个系统的整体碎片.

This behaviour, while increasing internal fragmentation, decreases overall fragmentation throughout the system.

来源: http://repo.or.cz/w/glibc.git/blob/HEAD:/malloc/malloc.c (尤其是阅读第108行)

Source: http://repo.or.cz/w/glibc.git/blob/HEAD:/malloc/malloc.c (Read line 108 in particular)

/*
...
Minimum allocated size: 4-byte ptrs:  16 bytes    (including 4 overhead)
...
*/

此外,glibc中malloc调用返回的所有地址都与以下地址对齐:2 * sizeof(size_t)字节.对于32位系统(例如您的系统),这是64位;对于64位系统,是128位.

Furthermore, all addresses returned by the malloc call in glibc are aligned to: 2 * sizeof(size_t) bytes. Which is 64 bits for 32-bit systems (such as yours) and 128 bits for 64-bit systems.

这篇关于为什么分配单个字节时地址不连续?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆