Keil MDK 使用malloc()&free(),stm32简单测试可用

1.8.9 Using malloc() when exploiting the C library

If heap support is required for bare machine C, you must implement _init_alloc() and__rt_heap_extend().

_init_alloc() must be called first to supply initial heap bounds, and  __rt_heap_extend() must be provided even if it only returns failure. Without  __rt_heap_extend(), certain library functionality is included that causes problems when you are writing bare machine C.
Prototypes for both  _init_alloc() and  __rt_heap_extend() are in  rt_heap.h.

以上摘自http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.subset.swdev.comp6/index.html



程序包含头文件:rt_heap.h,stdlib.h。注意不要勾选MicroLIB。

汇编代码中设置Heap大小,我设置为4KB。

Heap_Size       EQU     0x00004000

跟高级的方法如下:

简单的测试代码如下:

[cpp]  view plain  copy
  1. #define HEAP_BASE 0x20002558  
  2. #define HEAP_SIZE 0x00004000  
  3. #define HEAP_END  HEAP_BASE+HEAP_SIZE  
  4.     void testmem()  
  5.     {     
  6.     int *p,*k=NULL;  
  7.     int a=0;  
  8.     volatile int i=0;  
  9.     _init_alloc(HEAP_BASE,HEAP_END);  
  10.         while(1)  
  11.         {  
  12.             if(a>1000)break;  
  13.             p=(int*)malloc(a++);  
  14.             i=(unsigned int)p-(unsigned int)k;  
  15.             k=p;  
  16.             *p=a;  
  17.               
  18.         //free(p);  
  19.         }  
  20.           
  21.     }  
调试可看到如下结果:


其中p,k是两次malloc得到的地址,i为两次得到的mallac得到地址的间隔,需要注意malloc得到的内存是8字节对其的。a是写入的一个数据。该程序执行一段时间后会内存泄漏,因为没free,去掉free()的注释即可。以下是free(p)的调试结果:经过多次malloc后得到的内存地址始终是0x20002570。


总结:

  1. .If heap support is required for bare machine C, you must implement _init_alloc() and__rt_heap_extend().
  2. 分配的内存地址8byte对齐;
  3. #define HEAP_BASE 0x20002558这里的地址可以看*.map文件Heap_Mem的值。这里应该可以通过汇编和C的混合编程来实现,暂时没试。
饿死了,以上暂作笔记用,找时间再整理下测试下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值