Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!caip!clyde!cbatt!cbosgd!ihnp4!cuae2!ltuxa!ttrdc!levy From: levy@ttrdc.UUCP (Daniel R. Levy) Newsgroups: net.unix Subject: Re: strdup Message-ID: <1170@ttrdc.UUCP> Date: Mon, 1-Sep-86 23:58:21 EDT Article-I.D.: ttrdc.1170 Posted: Mon Sep 1 23:58:21 1986 Date-Received: Tue, 2-Sep-86 21:30:10 EDT References: <3325@brl-smoke.ARPA> <241@bsdpkh.UUCP> Organization: AT&T, Computer Systems Division, Skokie, IL Lines: 37 In article <241@bsdpkh.UUCP>, heff@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