Re: c question



* Adrian Hosey (ahosey@snowcrash.kiva.net) wrote:
> On  1 Oct, Chris Jones wrote:
>:  
>:  Why not just do:
>:  
>:  void function( char *string )
>:  {
>:  	if( string == NULL ) {
>:  		string = strdup( "default" );
>:  	}
>:  
>:  	/* ... */
>:  
>:  	free( string );
>:  
>:  }
>:  
>:  int main()
>:  {
>:  	function( "moo" );
>:  	function( NULL );
>:  }
>:  
>:  it does mean that you can't just call "function();" - you have to put
>:  a NULL as the argument, but it works just fine.
> 
> Until you get to free( string ), you were good up to there. In the two
> examples above, the first would try to free() a string constant (bad)
> the second would try to free() NULL (also bad). Generally I don't think
                   ^^^^^^^^^^^^^^^^^^
No it wouldn't.

> you want to free() something passed to you as a parameter because you
> don't always know how it was allocated. If there is a special case when
> that is what you want, it should be clearly documented, then the
> crashes can be blamed on the application programmer...
> 
> Michael's suggestion is probably the best for making default parameters.
> 
> 	- A
Tom.
-- 
            .-------------------------------------------------------.
    .^.     | Tom Gilbert, England | tom@tomgilbert.freeserve.co.uk |
    /V\     |----------------------| www.tomgilbert.freeserve.co.uk |
   // \\    | Sites I recommend:   `--------------------------------|
  /(   )\   | www.freshmeat.net www.enlightenment.org www.gnome.org |
   ^^-^^    `-------------------------------------------------------'



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