示例#1
0
文件: realloc.c 项目: Avanznow/rtems
void *realloc(
  void *ptr,
  size_t size
)
{
  uintptr_t old_size;
  char    *new_area;

  /*
   *  Do not attempt to allocate memory if in a critical section or ISR.
   */

  if (_System_state_Is_up(_System_state_Get())) {
    if (!_Thread_Dispatch_is_enabled())
      return (void *) 0;
  }

  /*
   * Continue with realloc().
   */
  if ( !ptr )
    return malloc( size );

  if ( !size ) {
    free( ptr );
    return (void *) 0;
  }

  if ( !_Protected_heap_Get_block_size(RTEMS_Malloc_Heap, ptr, &old_size) ) {
    errno = EINVAL;
    return (void *) 0;
  }

  /*
   *  Now resize it.
   */
  if ( _Protected_heap_Resize_block( RTEMS_Malloc_Heap, ptr, size ) ) {
    return ptr;
  }

  /*
   *  There used to be a free on this error case but it is wrong to
   *  free the memory per OpenGroup Single UNIX Specification V2
   *  and the C Standard.
   */

  new_area = malloc( size );

  if ( !new_area ) {
    return (void *) 0;
  }

  memcpy( new_area, ptr, (size < old_size) ? size : old_size );
  free( ptr );

  return new_area;

}
/*
 *  If the pointer is not in the heap, then we won't be able to get its
 *  size and thus we skip updating the statistics.
 */
static void rtems_malloc_statistics_at_free(
  void *pointer
)
{
  uintptr_t size;

  if (_Protected_heap_Get_block_size(RTEMS_Malloc_Heap, pointer, &size) ) {
    MSBUMP(lifetime_freed, size);
  }
}
static void rtems_malloc_statistics_at_malloc(
  void *pointer
)
{
  uintptr_t actual_size = 0;
  uint32_t current_depth;
  rtems_malloc_statistics_t *s = &rtems_malloc_statistics;

  if ( !pointer )
    return;

  _Protected_heap_Get_block_size(RTEMS_Malloc_Heap, pointer, &actual_size);

  MSBUMP(lifetime_allocated, actual_size);

  current_depth = (uint32_t) (s->lifetime_allocated - s->lifetime_freed);
  if (current_depth > s->max_depth)
      s->max_depth = current_depth;
}