[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Sv: Sv: Memory allocators






>Bjarke Hammersholt Roune wrote:
>>Actually, I like throwing an exception better than returning 0, partly
>>because its really, really, really a pain to have to check the return
value
>>of new all the time, partly because running out of memory is pretty fatal
to
>>the proper functioning of many or even most functions, so you don't want
to
>>catch the exception anyway. This is what I see as getting both utility
and
>>functionality "for free".
>
>In theory this is right, but in a function like this one:
>
>int SomeFunc (void)
>{
>  char *String1 = new [256];
>  char *String2 = new [1024];
>
>  // do something
>
>  delete[] String1;
>  delete[] String2;
>}
>
>(just a silly example. Imagine a function that really needs to allocate
the
>stuff dynamically).
>If the first allocation here fails, everything is fine. But if the second
>one fails we have a memory leak.

This is why using auto_ptr is important if you care about resource leaks
caused by exceptions.
It might be good idea to use the string class rather than c strings

Replace the above with something like :

int SomeFunc(void)
{
  auto_ptr<char> String1(new char [256]);
  auto_ptr<char> String2(new char [1024]);

 // do some thing

 // auto_ptr goes out of scope so it destroys its contents. -- dont have to
manually delete them
}

If the first allocation succeeds but the second fails the first allocation
is still deleted when it goes
out of scope.



Peter Burns