|
-
June 30th, 2010, 07:55 PM
#1
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;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|