ARM Technical Support Knowledge Articles

MAKING MALLOC AND FREE REENTRANT

Applies to: RTX166 Tiny Real-time Kernel

Answer


Information in this article applies to:


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

Article last edited on: 2004-06-07 12:20:44

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential