[RTT例程练习] 3.2 动态内存管理之rt_realloc和free
realloc 用于重新分配内存的场景。如果原先通过 malloc分配的空间过小,则可通过realloc重新分配大小。当然具体实现的时候分两种情况,如果原内存块后有足够的空间,则之间将原内存块扩大,如果不够,则重新寻找一个地方,将原数据也拷贝至此。
代码:
#include <rtthread.h> struct rt_thread thread1; static rt_uint8_t thread1_stack[512]; void thread1_entry(void* parameter) { int i,j = 1; char *ptr[10]; /* 用于放置10个分配内存块的指针*/ /* 对指针清零*/ for (i = 0; i <10; i ++) ptr[i] = RT_NULL; while(j--) { for (i = 0; i <10; i++) { /* 每次分配(1 <<i)大小字节数的内存空间*/ ptr[i] = rt_malloc(10); /* 如果分配成功*/ if (ptr[i] != RT_NULL) { rt_kprintf("get memory: 0x%x\n", ptr[i]); rt_realloc(ptr[i],16); /* 如果分配成功*/ if (ptr[i] != RT_NULL) { rt_kprintf("memory realloc success!\n"); /* 释放内存块*/ rt_free(ptr[i]); rt_kprintf("memory free success!\n"); ptr[i] = RT_NULL; } } } } } int rt_application_init() { rt_thread_init(&thread1, "thread1", thread1_entry, RT_NULL, &thread1_stack[0], sizeof(thread1_stack), 10, 100); rt_thread_startup(&thread1); return 0; }
结果:
get memory: 0x20000c58 memory realloc success! memory free success! get memory: 0x20000c58 memory realloc success! memory free success! get memory: 0x20000c58 memory realloc success! memory free success! get memory: 0x20000c58 memory realloc success! memory free success! get memory: 0x20000c58 memory realloc success! memory free success! get memory: 0x20000c58 memory realloc success! memory free success! get memory: 0x20000c58 memory realloc success! memory free success! get memory: 0x20000c58 memory realloc success! memory free success! get memory: 0x20000c58 memory realloc success! memory free success! get memory: 0x20000c58 memory realloc success! memory free success!