File I/O with Static Allocation

I am sure you won’t be surprised to learn that most (if not all) of the code presented in the book is derived from my past experimentations on the PIC18 and PIC16 over a few years… In particular the FileIO project started on the PIC18F8720 and was, back then, associated to a different set of low level routines (for Compact Flash FLASH memory cards).

Also during debugging of the PIC24 version, I used static memory allocation (it made inspecting data structures with MPLAB so much easier), so when recently one of my readers asked about the possibility to modify the code to allow for static allocation of the I/O buffers and MEDIA data structures, it was easy for me to provide an “alternative”…

In fact this is nothing but a quick debugging fix, though it could be just your ticket. Below you will find two simple functions designed to replace malloc() and free() that can be inserted at the top of the fileio.c code (and enabled when the macro DBG is defined):

#ifdef DBG
//----------------------------------------------------------------------
// debugging malloc and free
#define F_MAX 2 // max number of files open
MFILE F[F_MAX];
MEDIA disk;
unsigned char B[F_MAX][512];
int Fcount=0, Bcount=0;

void * malloc( unsigned size)
{
if ( size == 512)
{
if ( Bcount<F_MAX)
return (void *)B[Bcount++];
else
return NULL;
}
else if ( size == sizeof( MFILE))
{
if ( Fcount<F_MAX)
return (void *)&F[Fcount++];
else
return NULL;
}
else if ( size == sizeof( MEDIA))
{
return &disk;
}
else
return NULL;
} // malloc

void free( void *p)
{
if (( p == B[0])||( p == B[1]))
Bcount--;
else
Fcount--;
} // free
#endif

NOTE: Should you try to port the code (back) to the C18 compiler, keep in mind that you will need to be very careful to modify the linker script as well to allow for the large buffers requiring more than 256 bytes each … Check the C18 compiler manual for help on how to allocate objects that are larger than 256bytes …

This entry was posted in Tips and Tricks. Bookmark the permalink.