Re: memory leak in the code?
On Jan 5, 6:47 pm, "Daniel T." <danie...@earthlink.net> wrote:
George2 <george4acade...@yahoo.com> wrote:
Should I delete memory pointed by pointer a if there is
bad_alloc when allocating memory in memory pointed by
pointer b? I am not sure whether there will be memory leak
if I do not delete a.
[Code]
try {
a = new int [N];
b = new int [M];
} catch (bad_alloc)
{
// if a success, but b fail, should we try to delete[] a here to
avoid memory leak?
}
[/Code]
The proper way to do the code above is:
a = 0;
b = 0;
try {
a = new int [N];
b = new int [N];}
catch( bad_alloc ) {
delete [] a;
delete [] b;
}
But the best way is to turn 'a' and 'b' into vector<int>s.
Since when is the "best way" not the "proper way"? Your
solution is "correct", of course, as would be using
boost::scoped_array. But as you say, the best way is to use
std::vector< int >. Anything else is less good.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34