Sujet : Re: Fixing a sample from K&R book using cake static analyser
De : ldo (at) *nospam* nz.invalid (Lawrence D'Oliveiro)
Groupes : comp.lang.cDate : 23. Jun 2024, 00:30:23
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v57mqf$3vq0p$5@dont-email.me>
References : 1 2 3
User-Agent : Pan/0.158 (Avdiivka; )
On Sun, 23 Jun 2024 02:23:43 +0300, Anton Shepelev wrote:
Why are you so afraid of `goto' ...
Look up the concept of a “Nassi-Shneiderman diagram”. It allows arbitrary
nesting of complex code, with dynamic allocation going on, while
minimizing flow-control headaches. The example I posted was a simple one;
I have more complex ones if you want to see.
I think you forget to set np->name (and to free() it in
case of error).
Ah, didn’t notice that, since it was hidden in the middle of another line
of code. The fix is simple. And while I’m at it, it makes sense to factor
out the table entry disposal code into a separate routine.
void np_free(struct nlist *np)
{
if (np != NULL)
{
free(np->name);
free(np->defn);
} /*if*/
free(np);
} /*np_free*/
struct nlist *install(char *name, char *defn)
{
struct nlist *np = NULL;
struct nlist *result = NULL;
unsigned hashval;
do /*once*/
{
result = lookup(name);
if (result != NULL)
break;
np = (struct nlist *)calloc(1, sizeof struct nlist);
if (np == NULL)
break;
np->name = strdup(name);
if (np->name == NULL)
break;
np->defn = strdup(defn);
if (np->defn == NULL)
break;
hashval = hash(name);
np->next = hashtab[hashval];
hashtab[hashval] = np;
result = np;
np = NULL; /* so I don’t dispose of it yet */
}
while (false);
np_free(np);
return
result;
} /*install*/