NXP

uC/OS-II内存管理之OSMemCreate()代码可读性的一点改进

2019-07-12 11:44发布

个人感觉uC/OS-II内存管理之OSMemCreate(),在创建空余内存块链表时,可读性不好。 该函数源代码: OS_MEM *OSMemCreate (void *addr, INT32U nblks, INT32U blksize, INT8U *err) { #if OS_CRITICAL_METHOD == 3 /* Allocate storage for CPU status register */ OS_CPU_SR cpu_sr; #endif OS_MEM *pmem; INT8U *pblk; void **plink; INT32U i; #if OS_ARG_CHK_EN > 0 if (addr == (void *)0) { /* Must pass a valid address for the memory part. */ *err = OS_MEM_INVALID_ADDR; return ((OS_MEM *)0); } if (nblks < 2) { /* Must have at least 2 blocks per partition */ *err = OS_MEM_INVALID_BLKS; return ((OS_MEM *)0); } if (blksize < sizeof(void *)) { /* Must contain space for at least a pointer */ *err = OS_MEM_INVALID_SIZE; return ((OS_MEM *)0); } #endif OS_ENTER_CRITICAL(); pmem = OSMemFreeList; /* Get next free memory partition */ if (OSMemFreeList != (OS_MEM *)0) { /* See if pool of free partitions was empty */ OSMemFreeList = (OS_MEM *)OSMemFreeList->OSMemFreeList; } OS_EXIT_CRITICAL(); if (pmem == (OS_MEM *)0) { /* See if we have a memory partition */ *err = OS_MEM_INVALID_PART; return ((OS_MEM *)0); } plink = (void **)addr; /* Create linked list of free memory blocks */ pblk = (INT8U *)addr + blksize; for (i = 0; i < (nblks - 1); i++) { *plink = (void *)pblk; plink = (void **)pblk; pblk = pblk + blksize; } *plink = (void *)0; /* Last memory block points to NULL */ pmem->OSMemAddr = addr; /* Store start address of memory partition */ pmem->OSMemFreeList = addr; /* Initialize pointer to pool of free blocks */ pmem->OSMemNFree = nblks; /* Store number of free blocks in MCB */ pmem->OSMemNBlks = nblks; pmem->OSMemBlkSize = blksize; /* Store block size of each memory blocks */ *err = OS_NO_ERR; return (pmem); }
创建空余内存块链表时
原先是,pblk在循环开始前就指向第二个内存块,只需N-1次完成链表。 plink = (void **)addr; /* Create linked list of free memory blocks */ pblk = (INT8U *)addr + blksize; for (i = 0; i < (nblks - 1); i++) { *plink = (void *)pblk; plink = (void **)pblk; pblk = pblk + blksize; } *plink = (void *)0; /* Last memory block points to NULL */

现修改成循环前plink和pblk都指首地址,也就是第一个内存块的地址,有N个内存块就循环N次。这样感觉比较好理解偷笑 /* plink 和 pblk 进行循环前,都指向addr */ plink = (void **)addr; /* Create linked list of free memory blocks */ pblk = (INT8U *)addr; for (i = 0; i < nblks; i++) { /* N个内存块就循环N次 */ pblk = pblk + blksize; *plink = (void *)pblk; plink = (void **)pblk; } *plink = (void *)0; /* Last memory block points to NULL */