文章目錄
- RT-Thread 堆內存 檢查命令 free 實現及介紹
- rt_memory_info 函數驗證
RT-Thread 堆內存 檢查命令 free 實現及介紹
在RT-Thread系統中,通常可以通過rt_memory_info
函數獲取當前的堆內存使用信息,然后你可以包裝這個函數來顯示剩余的堆空間。rt_memory_info
實現見:
rt-thread/src/mem.c
:
void rt_memory_info(rt_uint32_t *total,rt_uint32_t *used,rt_uint32_t *max_used)
{if (total != RT_NULL)*total = mem_size_aligned;if (used != RT_NULL)*used = used_mem;if (max_used != RT_NULL)*max_used = max_mem;
}
rt-thread 中其實已經實現了cmd_free
函數,可以使用這個函數來查看當前堆的使用情況:
#ifdef RT_USING_HEAP
int cmd_free(int argc, char **argv)
{rt_uint32_t total = 0, used = 0, max_used = 0;rt_memory_info(&total, &used, &max_used);rt_kprintf("total : %d\n", total);rt_kprintf("used : %d\n", used);rt_kprintf("maximum : %d\n", max_used);return 0;
}
MSH_CMD_EXPORT_ALIAS(cmd_free, free, Show the memory usage in the system.);
#endif /* RT_USING_HEAP */
所以在終端執行free
命令即可查看堆的使用情況:
msh >help
RT-Thread shell commands:
list - list all commands in system
list_timer - list timer in system
list_mempool - list memory pool in system
list_memheap - list memory heap in system
list_msgqueue - list message queue in system
list_mailbox - list mail box in system
list_mutex - list mutex in system
list_event - list event in system
list_sem - list semaphore in system
list_thread - list thread
version - show RT - Thread version information
clear - clear the terminal screen
hello - say hello world
free - Show the memory usage in the system.
ps - List threads in the system.
help - RT - Thread shell help.
rt_memory_info 函數驗證
如下實現了一個測試函數,在函數開始的時候查看當前堆使用了多少,然后再進行rt_malloc(1024)
之后再查看下堆使用了多少,通過前后對比可以看出rt_memory_info
函數獲取的信息是否正確。
#include <rtthread.h>
#include <pthread.h>#define TEST_MALLOC_SIZE 1024static int mem_check_test(void)
{char *ptr = RT_NULL;rt_uint32_t total = 0, used_pre = 0, max_used = 0;rt_uint32_t used_next = 0;rt_memory_info(&total, &used_pre, &max_used);ptr = (char *)rt_malloc(TEST_MALLOC_SIZE);if (ptr == RT_NULL) {rt_kprintf("mem check test failed\n");return -RT_ENOMEM;}rt_memory_info(&total, &used_next, &max_used);if ((used_next - used_pre) != TEST_MALLOC_SIZE + 16) {rt_kprintf("mem check test failed\n""mem used_pre: %d, mem used_next:%d\n",used_pre, used_next);rt_free(ptr);return -RT_ERROR;}rt_kprintf("mem check test ok\n");rt_free(ptr);return RT_EOK;
}
INIT_APP_EXPORT(mem_check_test);
關于free
命令的本地測試如下:
通過執行free命令之后可以看到一共有多少heap和已經使用了多少。
通常需要在跑完測試用例后不能影響heap的大小,簡單點說就是你的測試case不能導致內存泄露。