问题描述
近日接到一客户需求,其欲在 STM32CubeIDE 中指定堆(Heap)的地址到某一专用的RAM 中。
问题分析
STM32CubeIDE 生成的工程中,默认的堆栈配置示意图如图 1 所示:
解决方法
通过 STM32CubeIDE 生成的工程中,会默认生成 sysmem.c。这个文件中的
__sbrk_heap_end 指针默认赋值为 NULL,我们只需要更改这个指针为目标地址即可达到期望。
例如:默认配置是“static uint8_t *__sbrk_heap_end = NULL;”我们希望将堆的地址分配到 0x20001000 为起始的空间上,可以这样做:
“static uint8_t *__sbrk_heap_end = (uint8_t*)0x20001000;”
注意:由于堆(heap)向上增长,栈(stack)向下增长,所以在手动更改堆的起始地址时,如果定义的堆和栈空间存在重叠区域,STM32CubeIDE 无法识别这种情形,用户应当避免这样的设置。
验证
在 STM32CubeIDE 生成的串口打印的工程,然后按照上面示例修改 sysmem.c 中的__sbrk_heap_end 参数。
可以看到 heap_pointer 指针通过 malloc 申请到的地址,已经指向了目标 RAM 范围内了。
注意,这里我们在 0x20001000 开始的位置申请了 10 个字节的空间,理论上heap_pointer 应当从 0x20001000 开始计算,但是由于 malloc 在申请的地址时,会占用 8个字节用来存储状态等信息,所以 heap_pointer 指针从 0x20001008 开始。这是STM32CubeIDE 使用了 newlib 库来实现 malloc 的机制所致,不影响用户的使用。
相关文章









