strdup

Daniel R. Levy levy at ttrdc.UUCP
Tue Sep 2 13:58:21 AEST 1986


In article <241 at bsdpkh.UUCP>, heff at bsdpkh.UUCP (Paul K Heffner) writes:

>> /* hjb 08/25/86 */
>> char * strdup(s)
>> char *s;
>> {
>> 	char *p;
>> 	extern char *malloc();
>> 	if(p=malloc(strlen(s)+1)) strcpy(p,s);
>> 	return p;
>> }

>The above code doesn't return a null if malloc fails

It DOESN'T???  Gee, then maybe you have a busted malloc().  If malloc()
fails, it should return the null pointer.  That is what is being tested in
the clause 'if(p=malloc(strlen(s)+1))'.  As so many people have expounded
in net.lang.c:  a null pointer is semantically the same as zero in the C
language (except for sizeof(), should pointers exist of sizes other than
sizeof(int)).

So if malloc() fails, p gets NULL and the return value is likewise NULL.
The if() simply keeps strcpy from trying to copy something into an invalid
buffer ("pointed to" by NULL) should malloc() fail.  Then the user can catch
the error instead of the program dumping core.  Simple huh?

>
>						Paul Heffner
>					{ihnp4,akgua,attmail}!bsdpkh!heff
-- 
 -------------------------------    Disclaimer:  The views contained herein are
|       dan levy | yvel nad      |  my own and are not at all those of my em-
|         an engihacker @        |  ployer or the administrator of any computer
| at&t computer systems division |  upon which I may hack.
|        skokie, illinois        |
 --------------------------------   Path: ..!{akgua,homxb,ihnp4,ltuxa,mvuxa,
	   go for it!  			allegra,ulysses,vax135}!ttrdc!levy



More information about the Comp.unix mailing list