Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #10342

Re: Handing initialization failures

From James Kuyper <jameskuyper@verizon.net>
Newsgroups comp.lang.c
Subject Re: Handing initialization failures
Date 2011-09-16 15:20 -0400
Organization A noiseless patient Spider
Message-ID <4E73A17C.4040807@verizon.net> (permalink)
References <013d83d0-af71-443a-b9a8-f40b0f28f061@h9g2000yqi.googlegroups.com>

Show all headers | View raw


On 09/16/2011 02:42 PM, Максим Фомин wrote:
> Hello.
> 
> I have a question regarding following problem. Let there is
> 
> struct Container{
> void *buffer;
> resource1 *res1;
> resource2 *res2;
> ...
> resource_n *res_n;
> };
> 
> pointer to which is return by function like container_alloc().
> Initialization of each member may fail and if last fails, and I need
> to free() all other initialized resources (otherwise there would be
> memory leakage). The situation become worse when any random "sub-
> resource" initialization may fail.
> 
> What is best way to deal whis this? There is obvious solution to free
> all previous allocated resources within "if" test block of each
> element, however I am looking for a better solution.

Set all of the pointers to null at start.
If any allocation fails, free ALL of the pointers.
Situations like this are part of the reason why the standard allows null
pointers to be passed to free().

Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Handing initialization failures Максим Фомин <maxim@maxim-fomin.ru> - 2011-09-16 11:42 -0700
  Re: Handing initialization failures James Kuyper <jameskuyper@verizon.net> - 2011-09-16 15:20 -0400
    Re: Handing initialization failures Максим Фомин <maxim@maxim-fomin.ru> - 2011-09-16 21:50 -0700
  Re: Handing initialization failures Ben Bacarisse <ben.usenet@bsb.me.uk> - 2011-09-16 20:26 +0100
  Re: Handing initialization failures ImpalerCore <jadill33@gmail.com> - 2011-09-16 12:29 -0700
  Re: Handing initialization failures jacob navia <jacob@spamsink.net> - 2011-09-16 21:45 +0200
    Re: Handing initialization failures Ian Collins <ian-news@hotmail.com> - 2011-09-17 08:15 +1200
  Re: Handing initialization failures "christian.bau" <christian.bau@cbau.wanadoo.co.uk> - 2011-09-16 13:41 -0700
  Re: Handing initialization failures Malcolm McLean <malcolm.mclean5@btinternet.com> - 2011-09-16 13:47 -0700
  Re: Handing initialization failures Paul N <gw7rib@aol.com> - 2011-09-17 04:04 -0700
    Re: Handing initialization failures James Kuyper <jameskuyper@verizon.net> - 2011-09-17 15:16 -0400
  Re: Handing initialization failures Nobody <nobody@nowhere.com> - 2011-09-17 19:16 +0100
  Re: Handing initialization failures Lauri Alanko <la@iki.fi> - 2011-09-21 19:09 +0000
    Re: Handing initialization failures Gene <gene.ressler@gmail.com> - 2011-09-22 06:32 -0700

csiph-web