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 优快云. 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;
}





### 如何在 STM32 中通过 `malloc` 设置堆内存大小 #### 1. 堆内存的概念及其重要性 STM32 的堆内存用于动态分配存储空间,通常由标准库中的 `malloc()` 和 `free()` 函数管理。如果堆内存不足,则可能导致程序崩溃或运行异常。因此,在嵌入式开发中合理配置堆内存至关重要。 #### 2. 默认堆内存的定义位置 默认情况下,STM32 的堆内存大小是在链接脚本文件(`.ld` 文件)中定义的。该文件指定了 RAM 起始地址和结束地址,并预留了一部分区域作为堆区[^1]。 #### 3. 修改堆内存大小的方法 可以通过修改 `.ld` 文件来调整堆内存大小。以下是具体操作: - 打开项目目录下的链接脚本文件(通常是 `STM32Fxxx_FLASH.ld` 或类似的名称),找到如下片段: ```text /* Define memory regions */ MEMORY { FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K /* Flash size depends on MCU model */ SRAM (rwx) : ORIGIN = 0x20000000, LENGTH = 128K /* SRAM size depends on MCU model */ } /* Specify the stack and heap sizes */ _stack_size = 0x400; /* Stack size in bytes */ _heap_size = 0xC000; /* Heap size in bytes */ ``` 在此处可以直接更改 `_heap_size` 的值以调整堆内存大小。例如,将其改为 `0x10000` 表示设置堆内存为 64KB[^2]。 #### 4. 动态扩展堆内存的方式 当堆内存不足以满足需求时,可以实现自定义的 `_sbrk` 函数来动态扩展堆内存。以下是一个简单的实现示例: ```c #include "stm32f4xx.h" #define HEAP_START ((void *)0x2000C000) // 堆起始地址 #define MAX_HEAP_SIZE (0x10000) // 最大堆大小(64KB) static uint32_t current_heap_end = (uint32_t)HEAP_START; _caddr_t _sbrk(int incr) { static unsigned char *heap_ptr = NULL; unsigned char *prev_heap_ptr; if (heap_ptr == NULL) { heap_ptr = HEAP_START; } prev_heap_ptr = heap_ptr; if (((unsigned long)(heap_ptr + incr)) > ((unsigned long)((char *)current_heap_end + MAX_HEAP_SIZE))) { return (NULL); // 如果超出最大堆范围则返回错误 } else { heap_ptr += incr; } return (caddr_t) prev_heap_ptr; } ``` 上述代码实现了 `_sbrk` 函数,允许动态扩展堆内存至指定的最大限制范围内[^3]。 #### 5. 测试堆内存分配情况 为了验证堆内存是否正常工作并检测可能产生的碎片化问题,可以在应用程序中加入以下测试逻辑: ```c #include <stdio.h> #include <stdlib.h> int main(void) { int i; void *ptr[10]; for (i = 0; i < 10; i++) { ptr[i] = malloc(100); if (ptr[i] != NULL) { printf("Allocated block %d at address: %p\n", i, ptr[i]); } else { printf("Failed to allocate block %d\n", i); } } for (i = 0; i < 10; i++) { free(ptr[i]); } while (1); } ``` 此代码模拟了多次连续申请与释放内存的过程,有助于观察是否存在内存泄漏或碎片化现象。 --- ###
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值