armandas wrote on Sunday, March 31, 2013:
I’ve been reading through the memory management code, trying to understand how it works and made a couple of changes as I went along. These changes can be applied to heap_2.c and heap_4.c files.
The first part changes the way pvReturn is assigned a value. The current code is not broken, but it was not clear to me why you would use pxPreviousBlock->pxNextFreeBlock when pxBlock points to the same location.
The changes in the second part may actually be usefull, as they get rid of a couple unused variables.
Here’s the diff. Let me know what you think.
--- heap_2.c
+++ heap_2v2.c
@@ -214,7 +214,7 @@
 			{
 				/* Return the memory space - jumping over the xBlockLink structure
 				at its start. */
-				pvReturn = ( void * ) ( ( ( unsigned char * ) pxPreviousBlock->pxNextFreeBlock ) + heapSTRUCT_SIZE );
+				pvReturn = ( void * ) ( ( ( unsigned char * ) pxBlock ) + heapSTRUCT_SIZE );
 
 				/* This block is being returned for use so must be taken out of the
 				list of free blocks. */
@@ -237,7 +237,7 @@
 					prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );
 				}
 				
-				xFreeBytesRemaining -= pxBlock->xBlockSize;
+				xFreeBytesRemaining -= xWantedSize;
 			}
 		}
 	}
@@ -259,17 +259,11 @@
 
 void vPortFree( void *pv )
 {
-unsigned char *puc = ( unsigned char * ) pv;
 xBlockLink *pxLink;
 
 	if( pv != NULL )
 	{
-		/* The memory being freed will have an xBlockLink structure immediately
-		before it. */
-		puc -= heapSTRUCT_SIZE;
-
-		/* This casting is to keep the compiler from issuing warnings. */
-		pxLink = ( void * ) puc;
+		pxLink = ( void * ) ( ( ( unsigned char * ) pv ) - heapSTRUCT_SIZE );
 
 		vTaskSuspendAll();
 		{