From owner-freebsd-hackers Wed Jul 7 13:56:50 1999 Delivered-To: freebsd-hackers@freebsd.org Received: from assaris.sics.se (assaris.sics.se [193.10.66.108]) by hub.freebsd.org (Postfix) with ESMTP id 4E4891506C for ; Wed, 7 Jul 1999 13:56:47 -0700 (PDT) (envelope-from assar@sics.se) Received: (from assar@localhost) by assaris.sics.se (8.9.3/8.7.3) id WAA20321; Wed, 7 Jul 1999 22:57:09 +0200 (CEST) To: Dag-Erling Smorgrav Cc: Jamie Howard , freebsd-hackers@FreeBSD.ORG, tech-userlevel@netbsd.org, tech@openbsd.org Subject: Re: Replacement for grep(1) (part 2) References: Mime-Version: 1.0 (generated by tm-edit 7.68) Content-Type: text/plain; charset=US-ASCII From: Assar Westerlund Date: 07 Jul 1999 22:57:07 +0200 In-Reply-To: Dag-Erling Smorgrav's message of "07 Jul 1999 21:15:05 +0200" Message-ID: <5laet8b2l8.fsf@assaris.sics.se> Lines: 46 X-Mailer: Gnus v5.5/Emacs 19.34 Sender: owner-freebsd-hackers@FreeBSD.ORG Precedence: bulk X-Loop: FreeBSD.ORG Dag-Erling Smorgrav writes: > - if ((realpat = malloc(strlen(pattern) + sizeof("^(") + > - sizeof(")$") + 1)) == NULL) > - err(1, "malloc"); > + realpat = grep_malloc(strlen(pattern) + sizeof("^(") > + + sizeof(")$") + 1); > strcpy(realpat, "^("); > strcat(realpat, pattern); > strcat(realpat, ")$"); Why not just use asprintf? > +void * > +grep_malloc(size_t size) > +{ > + void *ptr; > + > + if ((ptr = malloc(size)) == NULL) { > + errno = ENOMEM; > + err(1, "malloc"); > + } > + return ptr; > +} In this case it doesn't matter but in general this function is wrong. malloc(0) can return NULL. And besides, I really don't think this is a grep function but actually is useful for programs that don't have any strategy for handling out of memory errors and might as well die (with a descriptive error message, of course). Let's call it emalloc and let's put in somewhere where it can be used. void * emalloc (size_t sz) { void *tmp = malloc (sz); if (tmp == NULL && sz != 0) { errno = ENOMEM; err (1, "malloc %lu", (unsigned long)sz); } return tmp; } /assar To Unsubscribe: send mail to majordomo@FreeBSD.org with "unsubscribe freebsd-hackers" in the body of the message