Re: memory leak in the code?
"George" <George@discussions.microsoft.com> wrote in message
news:4BB7949B-C074-4310-A872-C5CFC96F2809@microsoft.com...
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]
thanks in advance,
George
Hi George,
First, if a memoryt allocation fails, the process will probably end. If
that's the case there's no need to worry about memory leaks. All memory
allocated to the process will be freed when the process ends.
If you know EXACTLY the size of an array required there's no real need to
use a container class. However I prefer the container class because when
passed into another function I can ask for it's size() rather than relying
on #defines or const int variables.
In your contrived example, it would be impossible to know which allocation
(a or b) failed. As Carl pointed out, each could be within their own
try/catch block. Of course, you would have to be able to recover from
either allocation failure to be worthwhile.
David - I agree that RAII and std::vector<> are both good things. However,
in your example, one doesn't have anything to do with the other. And
certainly they have nothing to to do with a bad_alloc.
- Arnie