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
23template <class T> T** AllocateMatrix(int rows, int cols);
24template <class T> T** AllocateMatrix(int rows, int cols, T value);
25template <class T> void FreeMatrix(T ** & matrix, int rows);
26
27char ** AllocateCharMatrix(int rows, int cols);
28void FreeCharMatrix(char ** & matrix, int rows);
29
30float ** AllocateFloatMatrix(int rows, int cols);
31void FreeFloatMatrix(float ** & matrix, int rows);
32
33double ** AllocateDoubleMatrix(int rows, int cols);
34void FreeDoubleMatrix(double ** & matrix, int rows);
35
36int ** AllocateIntMatrix(int rows, int cols);
37void FreeIntMatrix(int ** & matrix, int rows);
38
39short ** AllocateShortMatrix(int rows, int cols);
40void FreeShortMatrix(short ** & matrix, int rows);
41
42char *** AllocateCharCube(int n, int rows, int cols);
43void FreeCharCube(char *** & matrix, int n, int rows);
44
45
46// Template definitions follow ...
47//
48
49template <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
76template <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
88template <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