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

跟高級的方法如下:

簡單的測試代碼如下:

#define HEAP_BASE 0x20002558
#define HEAP_SIZE 0x00004000
#define HEAP_END  HEAP_BASE+HEAP_SIZE
	void testmem()
	{ 	
	int *p,*k=NULL;
	int a=0;
	volatile int i=0;
	_init_alloc(HEAP_BASE,HEAP_END);
		while(1)
		{
			if(a>1000)break;
			p=(int*)malloc(a++);
			i=(unsigned int)p-(unsigned int)k;
			k=p;
			*p=a;
			
		//free(p);
		}
		
	}
調試可看到如下結果:


其中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的混合編程來實現,暫時沒試。
餓死了,以上暫作筆記用,找時間再整理下測試下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章