oct-alloc.cc

Go to the documentation of this file.
00001 /*
00002 
00003 Copyright (C) 1996-2012 John W. Eaton
00004 
00005 This file is part of Octave.
00006 
00007 Octave is free software; you can redistribute it and/or modify it
00008 under the terms of the GNU General Public License as published by the
00009 Free Software Foundation; either version 3 of the License, or (at your
00010 option) any later version.
00011 
00012 Octave is distributed in the hope that it will be useful, but WITHOUT
00013 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
00014 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
00015 for more details.
00016 
00017 You should have received a copy of the GNU General Public License
00018 along with Octave; see the file COPYING.  If not, see
00019 <http://www.gnu.org/licenses/>.
00020 
00021 */
00022 
00023 #ifdef HAVE_CONFIG_H
00024 #include <config.h>
00025 #endif
00026 
00027 #include <new>
00028 
00029 #include "oct-alloc.h"
00030 
00031 void *
00032 octave_allocator::alloc (size_t size)
00033 {
00034   if (size != item_size)
00035     return ::new char [size];
00036 
00037   if (! head)
00038     {
00039       if (! grow ())
00040         return 0;
00041     }
00042 
00043   link *tmp = head;
00044   head = head->next;
00045   return tmp;
00046 }
00047 
00048 // FIXME -- if we free the last item on the list, shouldn't we
00049 // also free the underlying character array used for storage?
00050 
00051 void
00052 octave_allocator::free (void *p, size_t size)
00053 {
00054   if (size != item_size)
00055     ::delete [] (static_cast<char *> (p));
00056   else
00057     {
00058       link *tmp = static_cast<link *> (p);
00059       tmp->next = head;
00060       head = tmp;
00061     }
00062 }
00063 
00064 // Return TRUE for successful allocation, FALSE otherwise.
00065 
00066 bool
00067 octave_allocator::grow (void)
00068 {
00069   bool retval = true;
00070 
00071   char *start = new char [grow_size * item_size];
00072 
00073   if (start)
00074     {
00075       char *last = &start[(grow_size - 1) * item_size];
00076 
00077       char *p = start;
00078       while (p < last)
00079         {
00080           char *next = p + item_size;
00081           (reinterpret_cast<link *> (p)) -> next
00082             = reinterpret_cast<link *> (next);
00083           p = next;
00084         }
00085 
00086       (reinterpret_cast<link *> (last)) -> next = 0;
00087 
00088       head = reinterpret_cast<link *> (start);
00089     }
00090   else
00091     {
00092       typedef void (*error_handler_function) (void);
00093 
00094       error_handler_function f = std::set_new_handler (0);
00095       std::set_new_handler (f);
00096 
00097       if (f)
00098         f ();
00099 
00100       retval = false;
00101     }
00102 
00103   return retval;
00104 }
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Friends Defines