Re: c question
- From: Tom Gilbert <gilbertt tomgilbert freeserve co uk>
- To: Chris Jones <chris black-sun co uk>
- Cc: Gnome Devel <gnome-devel-list gnome org>
- Subject: Re: c question
- Date: Fri, 1 Oct 1999 13:41:01 +0000
* Chris Jones (chris@black-sun.co.uk) wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Hi
>
> > void function(char *string="default");
> >
> > and be able to call it with
> >
> > function();
>
> Why not just do:
>
> void function( char *string )
> {
> if( string == NULL ) {
> string = strdup( "default" );
> }
>
> /* ... */
>
> free( string );
^^^^^^^^^^^^^^^
Its a good idea not to try to free a constant string literal ;-)
>
> }
>
> int main()
> {
> function( "moo" );
^^^^^^^^^^^^^^^^^^
This line will segfault, as the function tries to free "moo", which
was never malloc'ed.
> 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.
This is the right solution though :)
I like:
void function( char *string )
{
int def=FALSE;
if( string == NULL ) {
string = strdup( "default" );
def=TRUE;
}
/* ... */
if(def)
free( string );
}
int main()
{
function( "moo" );
function( NULL );
}
But I'm just splitting hairs now.
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]