Dynamic memory allocation problem
I am trying to write a function to do dynamic memory allocation with a try catch block, so that I don't have to manually write a try catch block each time I want to allocate memory for an array. The code bellow is supposed to do that, but it outputs:
Allocated memory for small array
Segmentation fault
So apparently the function creates a copy of the array and allocates memory for the copy, but not for the original array. How do I fix this? Thanks in advance.
# include <iostream>
# include <fstream>
# include <string>
# include <cstring>
# include <sstream>
# include <time.h>
# include <iomanip>
# include <vector>
using namespace std;
template <class T>
bool SafeArrayAlloc(T *array, int Size)
{
try
{
array=new T[Size];
}
catch(bad_alloc&)
{
return false;
}
return true;
}
int main(int argc, char * argv[])
{
int big, small;
int *big_array, *small_array;
big=3000000000;
small=10;
if (!SafeArrayAlloc(&small_array, small))
{
cout <<"Unable to allocate memory for small array"<<endl;
}
else
{
cout <<"Allocated memory for small array"<<endl;
for (int i=0;i<small;i++) small_array[i]=0;
for (int i=0;i<small;i++) small_array[i]=i;
for (int i=0;i<small;i++) cout <<small_array[i]<<endl;
}
if (!SafeArrayAlloc(&big_array, big))
{
cout <<"Unable to allocate memory for big array"<<endl;
}
else
{
cout <<"Allocated memory for big array"<<endl;
for (int i=0;i<big;i++) big_array[i]=0;
for (int i=0;i<big;i++) big_array[i]=i;
for (int i=0;i<big;i++) cout <<big_array[i]<<endl;
}
return EXIT_SUCCESS;
}
Re: Dynamic memory allocation problem
bool SafeArrayAlloc(T*& array, int Size);
I am guessing that will fix your problem without looking that much. Also there is no need to create this function to implement a nothrow new.. just use
int* I = new (nothrow) int [array size] ();
http://www.cplusplus.com/reference/std/new/nothrow/
Re: Dynamic memory allocation problem
Thanks. It worked. I tried bool SafeArrayAlloc(T&* array, int Size) previously but it did not work. You are probably right that this function is not very useful, but I also wanted to write a function for multidimensional array allocation and I can't do that without getting this function to work. Thanks again.
Re: Dynamic memory allocation problem
Quote:
Originally Posted by
BrainInVat
Thanks. It worked. I tried bool SafeArrayAlloc(T&* array, int Size) previously but it did not work. You are probably right that this function is not very useful,
The real question is why did you need to write this when std::vector is available?
You even included <vector> in your code, but for some unexplained reason, you need to write this instead. :confused:
Regards,
Paul McKenzie
Re: Dynamic memory allocation problem
Quote:
Originally Posted by
BrainInVat
I also wanted to write a function for multidimensional array allocation and I can't do that without getting this function to work. Thanks again.
You should consider whether boost::multi_array solves your problem.