|
发表于 2018-12-21 22:40:52
|
显示全部楼层
用 gcc 編譯,malloc 和 free 是可以用的,不過一般不建議使用,因爲有碎片、缺管理等問題。
可以考慮用鏈表實現固定大小內存分配,簡單,適合實時應用,例如:
https://github.com/dukelec/cdnet/blob/master/utils/cd_debug.c
- typedef struct {
- list_node_t node;
- uint8_t data[DBG_STR_LEN]; /********************* 內存塊 *********************/
- int len;
- } dbg_node_t;
- static dbg_node_t dbg_alloc[DBG_LEN]; /********************* 分配內存 *********************/
- static list_head_t dbg_free = {0};
- static list_head_t dbg_tx = {0};
- void debug_init(void)
- {
- int i;
- for (i = 0; i < DBG_LEN; i++)
- list_put(&dbg_free, &dbg_alloc[i].node); /********************* 初始化內存 *********************/
- }
- void _dputs(char *str)
- {
- dbg_node_t *buf = list_get_entry_it(&dbg_free, dbg_node_t); /********************* 申請內存 *********************/
- if (buf) {
- buf->len = strlen(str);
- memcpy(buf->data, str, buf->len);
- list_put_it(&dbg_tx, &buf->node);
- } else {
- ......
- }
- }
- void debug_flush(void)
- {
- ......
- dbg_node_t *buf = list_get_entry_it(&dbg_tx, dbg_node_t);
- ......
- dbg_transmit(&debug_uart, buf->data, buf->len);
- list_put_it(&dbg_free, &buf->node); /********************* 釋放內存 *********************/
- }
- }
复制代码
|
|