Xref: utzoo comp.sources.wanted:15330 alt.sources.wanted:941 Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sdd.hp.com!spool.mu.edu!uwm.edu!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: <1991Feb19.004526.16033@onion.rain.com> Date: 19 Feb 91 00:45:26 GMT References: <1991Feb17.045913.17126@sbcs.sunysb.edu> <1991Feb17.164731.7564@onion.rain.com> <1991Feb18.154159.430@persoft.com> Lines: 65 In <1991Feb18.154159.430@persoft.com> dag@persoft.com (Daniel Glasser) writes: >In article <1991Feb17.164731.7564@onion.rain.com> I wrote: >>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); >>} > >Two minor nits... > >Nit #1: Why is rets static? Is there any reason to not leave it as automatic? > The value is not used between calls, and why waste data space when the > stack is available for these purposes? I'd suggest leaving the "static" > off. A creature of habit, I suppose. I've been bitten too often when I return something from a function that isn't static. (int's, for example.) For this case, it really doesn't matter. It's kinda like the braces around the malloc failure. They're not technically required, but it's not a bad habit. :-) >Nit #2: You should simplify your expression in the "malloc()", that is, > sizeof(char) * strlen(foo) + sizeof(char) > could be written > sizeof(char) * (strlen(foo) + 1) > I realize that this doesn't make it any less work for the CPU > (both are 1 add and 1 multiply), but to the latter form makes > it clearer what is being done (allocating enough space for > strlen(foo)+1 chars). Untrue. What if sizeof(char) != 1? Yours will break, and mine will work. {note: I don't personally know of places where this isn't true, but then again, some people think that sizeof (int) == sizeof (char *) :-} Also, sizeof() isn't taking anything extra. It's changed to a '1' by the COMPILER. Overall, I stand by my choice of + sizeof(char). I wrote this as an example for folks needing the functionality, not as a finely-tuned piece of code. You're more than welcome to improve on it. -Jeff -- Jeff Beadles jeff@onion.rain.com