I am trying to write a function which attempts to allocate memory 3d vectors and returns false if it is unable to allocate the memory. It is not working. I have pasted the code below.
The output I get is:Code:# include <iostream>
# include <fstream>
# include <string>
# include <cstring>
# include <sstream>
# include <time.h>
# include <iomanip>
# include <vector>
using namespace std;
template <class T>
bool SafeAlloc(vector<T> &v, int Size)
{
bool MemoryAllocated=true;
try
{
v.resize(Size, T(0));
}
catch(bad_alloc&)
{
MemoryAllocated=false;
}
return MemoryAllocated;
}
template <class T>
bool Create3DArray(vector< vector< vector<T> > > &array, int size1, int size2, int size3)
{
bool MemoryAllocated=true;
int i;
vector<T> v;
vector< vector<T> > matrix;
array.clear();
try
{
v.resize(size3, T(0));
matrix.resize(size2, v);
array.resize(size1, matrix);
}
catch (bad_alloc&)
{
MemoryAllocated=false;
}
return MemoryAllocated;
}
int main(int argc, char * argv[])
{
int big, small, big1d;
vector<double> big_array, small_array;
vector< vector< vector<double> > > big_array3d, small_array3d;
big1d=100000000;
big=500;
small=10;
if (!SafeAlloc(small_array, small))
{
cout <<"Unable to allocate memory for small array"<<endl;
}
else
{
cout <<"Allocated memory for small array"<<endl;
}
if (!SafeAlloc(big_array, big1d))
{
cout <<"Unable to allocate memory for big array"<<endl;
}
else
{
cout <<"Allocated memory for big array"<<endl;
}
if (!Create3DArray(small_array3d, small, small, small))
{
cout <<"Unable to allocate memory for small 3d array"<<endl;
}
else
{
cout <<"Allocated memory for small 3d array"<<endl;
}
if (!Create3DArray(big_array3d, big1d, big1d, big1d))
{
cout <<"Unable to allocate memory for big 3d array"<<endl;
}
else
{
cout <<"Allocated memory for big 3d array"<<endl;
}
if (!Create3DArray(big_array3d, big, big, big))
{
cout <<"Unable to allocate memory for big 3d array"<<endl;
}
else
{
cout <<"Allocated memory for big 3d array"<<endl;
}
return EXIT_SUCCESS;
}
Allocated memory for small array
Unable to allocate memory for big array
Allocated memory for small 3d array
Unable to allocate memory for big 3d array
Killed
The program crashes when it tries to allocate a large 3d vector, but works when it tries to allocate memory for an extremely large 3d vector or a small 3d vector. My function for doing the same thing with 1d vectors always works. It seems that the bad alloc is only caught when it is the first memory allocation in the try block. I am very confused. Thanks in advance for any help.