1. 程式人生 > >Keil MDK 使用malloc()&free(),stm32簡單測試可用。

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