malloc中 heap block 的 blocksize 大小问题

heap block 引发的思考

问题背景:


Implicit Free Lists


                  Any practical allocator needs some data structure that allows it to distinguish block boundaries and to distinguish between allocated and free blocks. Most allocators embed this information in the blocks themselves. One simple approach is shown in Figure 9.35.





malloc函数第一次申请出的是payload区域顶端的内存区域,返回的指针指向该处。


在payload之前还有一个header的区域,这个区域记录了block size,这里作者有点误导,由于是8byte align

于是在只有最底位(图中的a,用来记录block是否已经allocated还是free)


 首先要理解malloc中block size的原理


这个问题要能搞定,填对,不然下面的demo看了没用。。。

这是在32bit的机器上

对于上面那个题目的题解:

                  This problem touches on some core ideas such as alignment requirements, minimum block sizes, and header encodings. The general approach for determining the block size is to round the sum of the requested payload and the header size to the nearest multiple of the alignment requirement (in this case 8 bytes). For
example, the block size for the malloc(1) request is 4 + 1 = 5 rounded up to 8. The block size for the malloc(13)request is 13 + 4 = 17 rounded up to 24.

Request        Block size (decimal bytes) Block header (hex)
malloc(1)                   8                                          0x9
malloc(5)                  16                                         0x11
malloc(12)                16                                         0x11
malloc(13)                24                                         0x19




64bit的机器的malloc采用的是16byte对齐的!


在linux 64bit的 Ubuntu上做测试:

 




malloc(42)

这里申请 42byte的空间,malloc返回的连续内存空间是 64byte的


42 byte,由于开始有8byte的block size 区域,

42+8 = 50;

由于16byte对齐,于是对齐到64byte


至于最后的temp == 65 ,那是因为最后一位是用来提示该内存区域是否allocated。由于该bit 位等于1,于是,是allocated



上述测试代码:

 

/***********************************************************
code writer : EOF
code date : 2014.07.27
e-mail:jasonleaster@gmail.com

code purpose:
	Find out what beyond the payload location. :)

************************************************************/
#include <stdio.h>
#include <stdlib.h>

#define MACHINE_ADDRESS_LENGTH 64

void print_dec2bin(int dec_number)
//Just a simple function which translate decimal number into binary numebr
{
	int temp = 0;
	
	int to_be_print = 0;
	
	int array[MACHINE_ADDRESS_LENGTH];
	
	for(temp = 0;temp <  MACHINE_ADDRESS_LENGTH; temp++)
	{
		array[MACHINE_ADDRESS_LENGTH-temp-1] = dec_number%2;
		dec_number >>=1;
	}	

	for(temp = 0;temp <  MACHINE_ADDRESS_LENGTH; temp++)
	{
		printf("%d",array[temp]);
	}	

	printf("\n");
}

int main()
{
	int *ptr = NULL;
	
	int temp = 42;//how many bytes to be allocated

	printf("byte to be allocated, temp : %d\n",temp);

	ptr = (int *)malloc(temp);

	if(ptr == NULL)
	{
		printf("malloc failed\n");
		return 0;
	}
	else
	{
		*ptr = 2014;//just write some data into payload location.
	}

	temp = *(ptr - 2);//You may never forget that this code must be run on 64-bits machine, and ptr point to 'int'!!!Attention!!
			// otherwise you have to change 'ptr-2' into 'ptr-1'
	
	print_dec2bin(temp);
	
	printf("temp : %d\n",temp);

	free(ptr);
	return 0;
}


再三提示那个ptr-2!



如果多次malloc,除了最后一个block之外,每个block前后都有记录block的block size段,最后一个只有header blocksize






ubuntu2@ubuntu:~$ ./a.out
ptr_void:0x185f010
foo_void:0x185f030
ptr_void header size:32
ptr_void foot   size:32
foo_void header size:32
foo_void foot   size:135104

最后的size是不是blocksize,印证最后的block是没有foot block size记录块的!

测试demo:

/************************************************************************
code writer : EOF
code date : 2014.07.28
e-mail: jasonleaster@gmail.com

code purpose :
        test the block-size of each memory block which was allocated by
library function -- malloc().
        
        If there are something wrong with my code, please touch me by e-mail
or send me a message to my blog in CSDN. Thank you.
 
*************************************************************************/

#include <stdio.h>
#include <stdlib.h>

#define MACHINE_BITS    64      //the bits of this machine
#define BYTE            8       //one byte == eight bits

#define ALLOCATED_OR_NOT(bp)    ((unsigned long)(bp) & 0x1)
//@bp : block pointer which point into the start location of this block

#define GET_VALUE_LONG(ptr)             (*((long*)(ptr)))
//get the value of the location where ptr point to.

#define BLOCK_SIZE(bp)          ((GET_VALUE_LONG(bp))&(~0x7))
//get the block size

int main()
{
        void* ptr_void = malloc(sizeof(int));//allocate the first block.

        printf("ptr_void:%p\n",ptr_void);

        void* foo_void = malloc(sizeof(int));//allocate the second block.

        printf("foo_void:%p\n",foo_void);


        long block_size = BLOCK_SIZE((char*)ptr_void-(MACHINE_BITS/BYTE));//get the first block's header-block-size

        printf("ptr_void header size:%ld\n",block_size);
        printf("ptr_void foot   size:%ld\n",BLOCK_SIZE((char*)ptr_void+block_size-(MACHINE_BITS/BYTE)));
        //print out the foot-block-size


        block_size = BLOCK_SIZE((char*)foo_void-(MACHINE_BITS/BYTE));

        printf("foo_void header size:%ld\n",block_size);
        printf("foo_void foot   size:%ld\n",BLOCK_SIZE((char*)foo_void+block_size-(MACHINE_BITS/BYTE)));

        free(ptr_void);
        free(foo_void);
        return 0;
}





  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在 Keil ,使用 `malloc` 函数进行内存分配时,需要为其提供一个堆空间,否则会出现内存分配失败等问题。以下是在 Keil 初始化堆空间的步骤: 1. 首先在代码定义堆空间的起始地址和大小,例如: ```c #define HEAP_START 0x20000000 #define HEAP_SIZE 0x1000 ``` 这里定义了堆空间的起始地址为 `0x20000000`,大小为 `0x1000` 字节。 2. 在代码添加 `malloc` 函数的实现。可以使用 Keil 提供的 `rt_misc.c` 文件的 `__user_heap_extend` 函数作为 `malloc` 函数的实现,例如: ```c #include <stddef.h> #include <stdint.h> #define HEAP_START 0x20000000 #define HEAP_SIZE 0x1000 static uint8_t heap[HEAP_SIZE] __attribute__((section(".heap"))); void* __user_heap_extend(size_t incr) { static uint8_t* heap_end = NULL; uint8_t* prev_heap_end; if (heap_end == NULL) { heap_end = heap; } prev_heap_end = heap_end; if (heap_end + incr > heap + HEAP_SIZE) { // 内存不足,返回 NULL return NULL; } heap_end += incr; return prev_heap_end; } void* malloc(size_t size) { return __user_heap_extend(size); } void free(void* ptr) { // 空函数,不需要实现 } ``` 这里使用 `__attribute__((section(".heap")))` 将 `heap` 数组放在 `.heap` 段,以便在链接时将其放置在指定的地址。 3. 在代码调用 `malloc` 函数进行内存分配,例如: ```c int main() { int* p = (int*) malloc(sizeof(int)); if (p == NULL) { // 内存分配失败 return 1; } // 使用分配的内存 *p = 123; // 释放内存 free(p); return 0; } ``` 这样就完成了在 Keil 初始化堆空间的操作,可以使用 `malloc` 函数进行动态内存分配了。需要注意的是,由于 `malloc` 函数实现使用了静态变量,因此需要在 `__user_heap_extend` 函数将其声明为 `static` 变量,以避免链接时出现重复定义的错误。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值