libStatGen Software  1
MemoryAllocators.h
1 /*
2  * Copyright (C) 2010 Regents of the University of Michigan
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program. If not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #ifndef __MEMORY_ALLOCATORS_H__
19 #define __MEMORY_ALLOCATORS_H__
20 
21 #include <stdlib.h>
22 
23 template <class T> T** AllocateMatrix(int rows, int cols);
24 template <class T> T** AllocateMatrix(int rows, int cols, T value);
25 template <class T> void FreeMatrix(T ** & matrix, int rows);
26 
27 char ** AllocateCharMatrix(int rows, int cols);
28 void FreeCharMatrix(char ** & matrix, int rows);
29 
30 float ** AllocateFloatMatrix(int rows, int cols);
31 void FreeFloatMatrix(float ** & matrix, int rows);
32 
33 double ** AllocateDoubleMatrix(int rows, int cols);
34 void FreeDoubleMatrix(double ** & matrix, int rows);
35 
36 int ** AllocateIntMatrix(int rows, int cols);
37 void FreeIntMatrix(int ** & matrix, int rows);
38 
39 short ** AllocateShortMatrix(int rows, int cols);
40 void FreeShortMatrix(short ** & matrix, int rows);
41 
42 char *** AllocateCharCube(int n, int rows, int cols);
43 void FreeCharCube(char *** & matrix, int n, int rows);
44 
45 
46 // Template definitions follow ...
47 //
48 
49 template <class T> T** AllocateMatrix(int rows, int cols)
50 {
51  T ** matrix = new T * [rows];
52 
53  // Stop early if we are out of memory
54  if (matrix == NULL)
55  return NULL;
56 
57  for (int i = 0; i < rows; i++)
58  {
59  matrix[i] = new T [cols];
60 
61  // Safely unravel allocation if we run out of memory
62  if (matrix[i] == NULL)
63  {
64  while (i--)
65  delete [] matrix[i];
66 
67  delete [] matrix;
68 
69  return NULL;
70  }
71  }
72 
73  return matrix;
74 };
75 
76 template <class T> T** AllocateMatrix(int rows, int cols, T value)
77 {
78  T ** matrix = AllocateMatrix<T>(rows, cols);
79 
80  if (matrix != NULL)
81  for (int i = 0; i < rows; i++)
82  for (int j = 0; j < cols; j++)
83  matrix[i][j] = value;
84 
85  return matrix;
86 };
87 
88 template <class T> void FreeMatrix(T ** & matrix, int rows)
89 {
90  if (matrix == NULL)
91  return;
92 
93  for (int i = 0; i < rows; i++)
94  delete [] matrix[i];
95 
96  delete [] matrix;
97 
98  matrix = NULL;
99 };
100 
101 #endif
102