This is the mail archive of the
glibc-linux@ricardo.ecn.wfu.edu
mailing list for the glibc project.
Re: problem with malloc?
- To: glibc-linux at ricardo dot ecn dot wfu dot edu
- Subject: Re: problem with malloc?
- From: Kaz Kylheku <kaz at ashi dot footprints dot net>
- Date: Sun, 23 Apr 2000 15:27:13 -0700 (PDT)
- Reply-To: glibc-linux at ricardo dot ecn dot wfu dot edu
On Sun, 23 Apr 2000, Kervin wrote:
> Date: Sun, 23 Apr 2000 16:48:53 -0400 (EDT)
> From: Kervin <kpierre@winnie.fit.edu>
> Reply-To: glibc-linux@ricardo.ecn.wfu.edu
> To: glibc-linux@ricardo.ecn.wfu.edu
> Cc: Kaz Kylheku <kaz@ashi.footprints.net>
> Subject: Re: problem with malloc?
>
>
> > target = ( char * )malloc( (len+1)*sizeof( char ) );
> > strncpy( target, buffer, len );
>
> target = strdup(buffer);
Note that although strdup is a function in glibc, it is not a standard C
function. It is easy to write a tiny function that does what strdup does,
so there is little excuse for introducing a system depenency.
Also note that sizeof (char) is, by definition, one.
> or...
>
> target = ( char * )malloc( (len+1)*sizeof( char ) );
> memset(target, '\0',len+1);
> strcpy( target, buffer);
>
> when not sure, memset! : )
When not sure, think harder until sure. This memset is a complete waste of
cycles. The strcpy function does not require its target buffer to be
zero-filled, but merely large enough to hold a copy of the entire string.
It does require a valid pointer, however. The malloc function may return
null and that needs to be tested before using the pointer.