GNU Octave  3.8.0
A high-level interpreted language, primarily intended for numerical computations, mostly compatible with Matlab
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
oct-alloc.cc
Go to the documentation of this file.
1 /*
2 
3 Copyright (C) 1996-2013 John W. Eaton
4 
5 This file is part of Octave.
6 
7 Octave is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3 of the License, or (at your
10 option) any later version.
11 
12 Octave is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
16 
17 You should have received a copy of the GNU General Public License
18 along with Octave; see the file COPYING. If not, see
19 <http://www.gnu.org/licenses/>.
20 
21 */
22 
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26 
27 #include <new>
28 
29 #include "oct-alloc.h"
30 
31 void *
33 {
34  if (size != item_size)
35  return ::new char [size];
36 
37  if (! head)
38  {
39  if (! grow ())
40  return 0;
41  }
42 
43  link *tmp = head;
44  head = head->next;
45  return tmp;
46 }
47 
48 // FIXME: if we free the last item on the list, shouldn't we
49 // also free the underlying character array used for storage?
50 
51 void
52 octave_allocator::free (void *p, size_t size)
53 {
54  if (size != item_size)
55  ::delete [] (static_cast<char *> (p));
56  else
57  {
58  link *tmp = static_cast<link *> (p);
59  tmp->next = head;
60  head = tmp;
61  }
62 }
63 
64 // Return TRUE for successful allocation, FALSE otherwise.
65 
66 bool
68 {
69  bool retval = true;
70 
71  char *start = new char [grow_size * item_size];
72 
73  if (start)
74  {
75  char *last = &start[(grow_size - 1) * item_size];
76 
77  char *p = start;
78  while (p < last)
79  {
80  char *next = p + item_size;
81  (reinterpret_cast<link *> (p)) -> next
82  = reinterpret_cast<link *> (next);
83  p = next;
84  }
85 
86  (reinterpret_cast<link *> (last)) -> next = 0;
87 
88  head = reinterpret_cast<link *> (start);
89  }
90  else
91  {
92  typedef void (*error_handler_function) (void);
93 
94  error_handler_function f = std::set_new_handler (0);
95  std::set_new_handler (f);
96 
97  if (f)
98  f ();
99 
100  retval = false;
101  }
102 
103  return retval;
104 }