1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Dynamic memory allocation with try catch block

Discussion in 'C++' started by BrainInVat, Jul 1, 2010.

  1. BrainInVat

    BrainInVat New Member

    Joined:
    Jul 1, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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.
    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 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;
    }
     

Share This Page