simbasaurus
Programmer
- May 26, 2007
- 3
Hello!
I am trying to make sure that I clean up and free all the resources that I allocate in my code.
In the following code, I am assuming that if new throws bad_alloc, than the value of array1 or array2 is unmodified,
that is, they remain NULL.
In this case, if allocation of array1 succeeds, and allocation of array2 fails, then array1 will be deallocated.
What if new dows modify the value of the int* array2 even if second allocation does fail? Then I will call delete on a value that is undefined!!
I tried this code in Ubuntu using gcc, and when the second allocation fails, then array2 remains NULL, so there is no danger. But is this true for all compilers and systems?
I don't really know what the standard days.
class TwoIntArrays
{
public:
TwoIntArrays();
~TwoIntArrays();
private:
void free_resorces();
int* array1;
int* array2;
};
TwoIntArrays::TwoIntArrays()
{
array1 = NULL;
array2 = NULL;
try{
array1 = new int[200000];
array2 = new int[1000000000];
}
catch(bad_alloc&)
{
free_arrays();
throw;
}
}
~TwoIntArrays()
{
free_arrays();
}
void free_arrays()
{
delete array1;
delete array2;
}
Thank you in advance.
Simbasaurus.
I am trying to make sure that I clean up and free all the resources that I allocate in my code.
In the following code, I am assuming that if new throws bad_alloc, than the value of array1 or array2 is unmodified,
that is, they remain NULL.
In this case, if allocation of array1 succeeds, and allocation of array2 fails, then array1 will be deallocated.
What if new dows modify the value of the int* array2 even if second allocation does fail? Then I will call delete on a value that is undefined!!
I tried this code in Ubuntu using gcc, and when the second allocation fails, then array2 remains NULL, so there is no danger. But is this true for all compilers and systems?
I don't really know what the standard days.
class TwoIntArrays
{
public:
TwoIntArrays();
~TwoIntArrays();
private:
void free_resorces();
int* array1;
int* array2;
};
TwoIntArrays::TwoIntArrays()
{
array1 = NULL;
array2 = NULL;
try{
array1 = new int[200000];
array2 = new int[1000000000];
}
catch(bad_alloc&)
{
free_arrays();
throw;
}
}
~TwoIntArrays()
{
free_arrays();
}
void free_arrays()
{
delete array1;
delete array2;
}
Thank you in advance.
Simbasaurus.