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