Deutsch English Français Italiano |
<87wmmfq4if.fsf@bsb.me.uk> View for Bookmarking (what is this?) Look up another Usenet article |
Path: ...!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Ben Bacarisse <ben@bsb.me.uk> Newsgroups: comp.lang.c Subject: Re: Fixing a sample from K&R book using cake static analyser Date: Sun, 23 Jun 2024 12:31:52 +0100 Organization: A noiseless patient Spider Lines: 65 Message-ID: <87wmmfq4if.fsf@bsb.me.uk> References: <v53sl1$35qt7$1@dont-email.me> <v558hv$3dskb$1@dont-email.me> <20240623034624.135@kylheku.com> MIME-Version: 1.0 Content-Type: text/plain Injection-Date: Sun, 23 Jun 2024 13:31:52 +0200 (CEST) Injection-Info: dont-email.me; posting-host="8e298ef9233142ad2625f347aab31424"; logging-data="349947"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX195dh00RKDR0QtePhn29MmcLAs1HFw7YjM=" User-Agent: Gnus/5.13 (Gnus v5.13) Cancel-Lock: sha1:bdRsCVQQM9ADS4xgsMOt8mXmv58= sha1:Y6rxBbyvqRLOLT0m364v6eLg2NQ= X-BSB-Auth: 1.15a2c6e593a79d2d2189.20240623123152BST.87wmmfq4if.fsf@bsb.me.uk Bytes: 2964 Kaz Kylheku <643-408-1753@kylheku.com> writes: >> On Fri, 21 Jun 2024 09:45:21 -0300, Thiago Adams wrote: >> >>> Page 145, The C programming Language 2 Edition >>> >>> /* install: put (name, defn) in hashtab */ >>> struct nlist *install(char *name, char *defn) >>> { >>> struct nlist *np; >>> unsigned hashval; >>> >>> if ((np = lookup(name)) == NULL) { /* not found */ >>> np = (struct nlist *) malloc(sizeof(*np)); >>> if (np == NULL || (np->name = strdup(name)) == NULL) >>> return NULL; >>> hashval = hash(name); >>> np->next = hashtab[hashval]; >>> hashtab[hashval] = np; >>> } else /* already there */ >>> free((void *) np->defn); /* free previous defn */ >>> >>> if ((np->defn = strdup(defn)) == NULL) >>> return NULL; >>> return np; >>> } [snip attempts at tidying up...] > Watch and learn: > > struct nlist *install(char *name, char *defn) > { > struct nlist *existing = lookup(name); > > if (existing) { > return existing; > } else { > struct nlist *np = calloc(1, sizeof (struct nlist)); > char *dupname = strdup(name); > char *dupdefn = strdup(defn); > unsigned hashval = hash(name); > > if (np && dupname && dupdefn) { > np->name = dupname; > np->defn = dupdefn; > np->next = hashtab[hashval]; > hashtab[hashval] = np; > return np; > } > > free(dupdefn); > free(dupname); > free(np); > > return NULL; > } > } You've over-simplified. The function needs to replace the definition with a strdup'd string (introduction another way to fail) when the name is found by lookup. It's just another nested if that's needed. I don't get why the goto crowd want to complicate it so much. -- Ben.