Keil Logo

RTX166 TINY: MAKING MALLOC AND FREE REENTRANT


Information in this article applies to:

  • C166 Version 3.12
  • C166 Version 4.03

QUESTION

How 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.

ANSWER

You 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 ALSO

Last Reviewed: Monday, June 7, 2004


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.