| |||||
Technical Support Support Resources
Product Information | RTX166 TINY: MAKING MALLOC AND FREE REENTRANTInformation in this article applies to:
QUESTIONHow can I make the memory allocation routines (malloc, free, realloc, and calloc) reentrant? I'm using RTX166 Tiny and want to make sure that these routines are reentrant. ANSWERYou must protect these routines from being re-entered. You can use a global variable as a semaphore to do this. For example:
unsigned char semaphore_alloc = 0; // 0 = Memory allocation routines are available
#pragma disable // Disable Interrupts
unsigned char get_semaphore (char *semptr)
{
if (*semptr == 0) // Semaphore is available
{
(*semptr)++; // Get it
return (1); // Return Success
}
return (0); // Failure - wait for semaphore
}
#pragma disable // Disable Interrupts
void put_semaphore (char *semptr)
{
(*semptr)--; // Put Semaphore Back
}
void func (void)
{
char *buf;
//------------------------------------------------------
// Get the alloc semaphore and allocate a 100-byte
// buffer. Then return the semaphore.
//------------------------------------------------------
while (get_semaphore (&semaphore_alloc) == 0)
os_wait (K_TMO, 10, 0);
buf = malloc (100);
put_semaphore (&semaphore_alloc);
//------------------------------------------------------
// Get the alloc semaphore and free the buffer.
//------------------------------------------------------
while (get_semaphore (&semaphore_alloc) == 0)
os_wait (K_TMO, 10, 0);
free (buf);
put_semaphore (&semaphore_alloc);
}
SEE ALSOLast Reviewed: Monday, June 07, 2004 | ||||
| |||||