l i n u x - u s e r s - g r o u p - o f - d a v i s
Next Meeting:
July 7: Social gathering
Next Installfest:
Latest News:
Jun. 14: June LUGOD meeting cancelled
Page last updated:
2003 Mar 21 10:22

The following is an archive of a post made to our 'vox-tech mailing list' by one of its subscribers.

Report this post as spam:

(Enter your email address)
Re: [vox-tech] malloc() is ... old school?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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

"Micah J. Cowan" wrote:

> On Thu, Mar 20, 2003 at 10:15:43AM -0800, Tim Riley wrote:
> >
> >
> > > The first library had malloc(). Always
> > > using calloc() would be a ridiculously inefficient way to obtain
> > > memory if you're going to just set it again anyway.
> >
> > It might seem inefficient to set memory twice, but you're looking
> > at it from the CPU's point of view. Instead, by looking at it from
> > the programmer's point of view, the extra nanoseconds it takes
> > to always get a clean data structure is worth hours of time savings
> > by not having to trace a core dump.
> You're saying that you'd rather have your program silently set the
> wrong memory location than to vomit? In my experience, the earlier in
> the development stage you catch a bug, the better.
> What situation are you thinking of where an accidentally unset,
> malloc()ed structure would cause a core dump upon access that would
> not be duplicated had calloc() been used?

The vulnerability with malloc() occurs when working with pointers.
It's common to test if a pointer has been set
by placing it inside an "if" statement before referencing it.
If you always use calloc(), all of your pointers will be
initialized with zero. For the following example
it's clear that a core dump might occur; however, if the program were
1000 lines long and the variables set in different locations, tracing
could be a bear.

typedef struct
    char *name;
    char *address;
    char *city;
    char *state;
    char *zip_code;

int main( int argc, char **argv )
    PERSON *person = malloc( sizeof( PERSON ) );

    person->name = "fred";

    if ( person->name && person->zip_code )
        printf( "For person = %s, got zip code = %s\n",
                person->name, person->zip_code );

If calloc() had been used, no one would have noticed the delay and no
core would be dumped.



vox-tech mailing list

LUGOD Group on LinkedIn
Sign up for LUGOD event announcements
Your email address:
LUGOD Group on Facebook
'Like' LUGOD on Facebook:

Hosting provided by:
Sunset Systems
Sunset Systems offers preconfigured Linux systems, remote system administration and custom software development.

LUGOD: Linux Users' Group of Davis
PO Box 2082, Davis, CA 95617
Contact Us

LUGOD is a 501(c)7 non-profit organization
based in Davis, California
and serving the Sacramento area.
"Linux" is a trademark of Linus Torvalds.

Sponsored in part by:
Sunset Systems
Who graciously hosts our website & mailing lists!