Xref: utzoo comp.sources.wanted:15310 alt.sources.wanted:934 Path: utzoo!utgpu!cs.utexas.edu!wuarchive!uunet!ogicse!pdxgate!qiclab!onion!jeff From: jeff@onion.rain.com (Jeff Beadles) Newsgroups: comp.sources.wanted,alt.sources.wanted Subject: Re: What is strdup() supposed to do? Does anyone have a copy? Message-ID: <1991Feb17.164731.7564@onion.rain.com> Date: 17 Feb 91 16:47:31 GMT References: <1991Feb14.050716.9501@shibaya.lonestar.org> <1991Feb17.045913.17126@sbcs.sunysb.edu> Lines: 62 In <1991Feb17.045913.17126@sbcs.sunysb.edu> cbrown@eeserv1.ic.sunysb.edu (Charles T Brown) writes: > >Well, having learned C with Microsoft C, I looked it up. > >Basically: > >char * strdup (s) > >char * s; >{ > char * rets; > > rets=malloc (sizeof (char) * strlen (s)); > > strcpy (rets, s); > > return rets; >} Please folks, if you're going to answer a question, please do it correctly. There are two rather serious bugs with this function. 1) If malloc returns an error, it's ignored and the program blindly continues. 2) You're not malloc'ing enough space for the string! You **MUST** malloc strlen(str) + 1! The +1 is for the trailing null that is added to the end of every strcpy'ed string. Actually, malloc and strlen should also be declared, but that's possibly different for various systems. Strcpy could also return an error, but I don't think that I've ever seen someone check for it. :-) Here's an updated and working version of strdup() char * strdup (s) char *s; { static char *rets; extern char *malloc(); /* Might be extern void *malloc(); */ extern int strlen(); rets=malloc (sizeof (char) * strlen (s) + sizeof(char) ); /* Malloc failed. Oops! */ if (!rets) { return((char *)0); } (void) strcpy (rets, s); return (rets); } -Jeff -- Jeff Beadles jeff@onion.rain.com