[vox-tech] malloc() is ... old school?

Tim Riley vox-tech@lists.lugod.org
Fri, 21 Mar 2003 14:45:37 -0800


Jeff Newmiller wrote:

> On Fri, 21 Mar 2003, Tim Riley wrote:
>

<snip>

>
> > >
> > >   Especially this one by the author of the FreeBSD C Library (last paragraph):
> > >     http://groups.google.com/groups?q=NULL+calloc()+group:comp.lang.c+author:Chris+author:Torek&selm=18764%40dog.ee.lbl.gov
>
> Tim, I don't get the impression you actually read this last URL.
>

Very true -- too many words. My simple mind looks for simple explanations
located in simple sentences.

The truth of the matter is that I've never been
burned using the following code:

char *memory = (char *)0;

if ( !memory )
{
    printf( "memory is not set\n" );
}

If instead the code were:

char *memory = (char *)0;

if ( memory != NULL )
{
    printf( "memory is not set\n" );
}
else
{
    printf( "NULL is defined as %d\n", NULL );
}

and a number were outputted, then calloc() alone will not
suffice as a memory allocation function.
Then the following would be required:

char *memory = NULL;

if ( memory != NULL )
{
    printf( "memory is not set\n" );
}

Is this your point?

If it is, this contradicts "The C Programming Language -- ANSI C"
by Kernighan and Ritchie on page 102. It says, "...the constant zero
may be assigned to a pointer, and a pointer may be compared with
the constant zero. The symbolic constant NULL is often used in place
of zero as a mnemonic to indicate more clearly that this is a special value
for a pointer."

This implies that NULL always equals zero. Therefore,
it is safe to use calloc() to allocate memory to
structures with pointers and use those pointers in
"if" statements like this:

PERSON *person = (PERSON *)calloc( 1, sizeof( PERSON ) );

if ( !person )
{
    fprintf( stderr,
             "Memory allocation failed in %s/%s()\n",
             __FILE__, __FUNCTION__ );
    exit( 1 );
}

if ( person->zip_code )
{
    printf( "The zip code is populated with %s\n",
            person->zip_code );
}
else
{
    printf( "The zip code is not populated.\n" );
}

and the behavior will be the not populated statement outputted.

It is my preference to use calloc() alone instead of malloc() with
a bunch of initializations to avoid unnecessary typing.

>

<snip>