Re: memory leak in the code?
On Jan 5, 3:04 pm, George2 <george4acade...@yahoo.com> wrote:
Hello everyone,
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]
Interesting problem...
In theory in the above case you could do something like the following:
int * a = 0;
int * b = 0;
try {
a = new int [N];
try{
b = new int[M];
}
catch {bad_alloc){
delete a;
/* b didnt get allocated */
return;
}
/* delete a,b */
return;
}
catch bad_alloc{
/* neither a or b got allocated */
return;
}
However if looked at from a practical viewpoint, In case of
bad_alloc the most likely cause is that the system has run out of
memory.
Firstly It is a reasonable idea to try to detect bad_alloc
exceptions.
The problem then is once detected, what to do about them?
Its certainly useful ( IMO essential , at least polite) to try to
report this to the user, for which you need to catch the exception,
But bear in mind that you are equivalent to the drowning man in the
flooded room gulping the last bit of air, IOW you don't want to even
attempt any more heap allocations if at all possible, but pretty much
anything you do to output a diagnostic to the user may request
allocations. Neveretheless in this sitaution things can't get much
worse, so you should probably try doing the diagnostic (by calling
some code designed for this particular situation) and quit the
application if thats acceptable.
The point of this is...
If that's the strategy, you adopt then any dangling pointers will be
cleaned up by the system so its not worth worrying about them in
practise. Its also simple. You have done the right thing by the user.
Its their problem now.
If that strategy is unacceptable and you hope to continue the app,
then you are into a much more complicated ballgame. You have to find
some way to have some scratch space so you can then set about trying
the complicated task of regaining a useful amount of heap, and you
will need to deal with raw pointers owning heap real estate such as
'a'.
Another answer is. Dont use new, at least not in functions. If at all
possible allocate in class constructors and release in destructors.
(RAII) Then you will find that the problem is dealt with
automatically, because the destructor for the class allocated on the
stack is called automatically when an exception is thrown. This is how
most std::library types work under the hood (std::string , containers
etc
Smart pointers are another option rather than raw pointers.
regards
Andy Little