1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
// MemoryTest.h
#ifndef MEMORYTEST_H
#define MEMORYTEST_H
template <class type1, class type2>
void allocateData1DbyMalloc(type1**, type2);
template <class type1>
void deAllocateData1DbyFree(type1**);
template <class type1, class type2>
void allocateData2DbyMalloc(type1***, type2, type2);
template <class type1, class type2>
void destroyMatrix2DbyFree(type1***, type2);
#endif
//MemoryTest.cpp file contains the definition of the function which were declared in MemoryTest.h file.
#include "MemoryTest.h"
#include<cstdlib>
#include <typeinfo>
#include <cstring>
#include<iostream>
template <class type1, class type2>
void allocateData1DbyMalloc(type1** data1D, type2 nRow)
{
// cout << typeid(type1).name() << " " << typeid(**data1D).name() << "
" << typeid(*data1D).name() << " " << typeid(data1D).name() << endl;
*data1D = (type1*)malloc(nRow * sizeof(type1));
if (data1D == NULL) {
printf("ERROR: out of memory\n");
}
}
template <class type1>
void deAllocateData1DbyFree(type1** data1D)
{
// std::cout << typeid(type1).name() << " " << typeid(data1D).name() <<
" " << typeid(*data1D).name() << std::endl;
free(*data1D);
}
template <class type1, class type2>
void allocateData2DbyMalloc(type1*** data2D, type2 nRow, type2 nColumn)
{
*data2D = (type1 * *)malloc(sizeof(type1*) * nRow);
if (data2D == NULL) {
printf("ERROR: out of memory\n");
}
for (int i = 0; i < nRow; i++) {
(*data2D)[i] = (type1*)malloc(sizeof(type1) * nColumn);
if ((*data2D)[i] == NULL) {
printf("ERROR: out of memory\n");
}
}
}
template <class type1, class type2>
void destroyMatrix2DbyFree(type1*** data2D, type2 numberOfRow) {
// std::cout << typeid(type1).name() << " " << typeid(**data2D).name()
<< " " << typeid(*data2D).name() << " " << typeid(data2D).name() <<
std::endl;
for (int row = 0; row < numberOfRow - 1; row++)
free((*data2D)[row]);
free(*data2D);
}
//Main.cpp contain the vector and Matrix array which are declared inside of a main function. For the allocation of the memory it called to MemoryTest.h.
#include "MemoryTest.h"
int main() {
int n = 4;
float* constrainVector;
allocateData1DbyMalloc(&constrainVector, n);
constrainVector[0] = 6.0;
constrainVector[1] = 25.6;
constrainVector[2] = -11.2;
constrainVector[3] = 12.7;
deAllocateData1DbyFree(&constrainVector);
float** matrix2D;
allocateData2DbyMalloc(&matrix2D, n, n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix2D[i][j] = (double)(i+j);
destroyMatrix2DbyFree(&matrix2D, n);
return 0;
}
|