*BSD News Article 33562


Return to BSD News archive

Xref: sserve comp.os.386bsd.questions:11960 comp.os.386bsd.development:2361 comp.os.386bsd.misc:2956
Path: sserve!newshost.anu.edu.au!harbinger.cc.monash.edu.au!yarrina.connect.com.au!warrane.connect.com.au!kralizec.zeta.org.au!not-for-mail
From: bde@kralizec.zeta.org.au (Bruce Evans)
Newsgroups: comp.os.386bsd.questions,comp.os.386bsd.development,comp.os.386bsd.misc
Subject: Re: Why does FreeBSD 1.1.5 say gets() is unsafe?
Date: 1 Aug 1994 07:26:31 +1000
Organization: Kralizec Dialup Unix Sydney - +61-2-837-1183, v.32bis v.42bis
Lines: 28
Message-ID: <31h4u7$9os@kralizec.zeta.org.au>
References: <30lrf3$2ii@acmez.gatech.edu> <jmonroyCts1rL.96o@netcom.com> <31f1v8$2lg@mozo.cc.purdue.edu> <31gvf1$h19@starbase.neosoft.com>
NNTP-Posting-Host: kralizec.zeta.org.au

In article <31gvf1$h19@starbase.neosoft.com>,
Peter da Silva <peter@Starbase.NeoSoft.COM> wrote:
>In article <31f1v8$2lg@mozo.cc.purdue.edu>,
>Ben Jackson <bj@staff.cc.purdue.edu> wrote:
>>Test what you MEAN, sheesh!  That will fail if your buffer is too short
>>to hold the line, or if there is no newline in the input stream.  If
>>you don't want to write on a null pointer, TEST THE POINTER YOU'RE
>>WRITING ON.  Duh:
>
>>	if (fgets(buf, sizeof(buf), stdin) && result = strchr(buf, '\n'))
>>		*result = '\0';

The NULL pointer references are safer if they cause a core dump.  Now long
lines are silently split.

>You *do* need another temporary, though, because otherwise result will be
>pointing to the wrong place. Alternatively, you can do this:
>
>>	if (fgets(buf, sizeof(buf), stdin) && result = strchr(buf, '\n')) {
>>		*result = '\0';
>	        result = buf;
>	}
>
>But I think an explicit temp will be easier to optimise.

fgetln() is more optimal to begin with.  I must use it someday.
-- 
Bruce Evans  bde@kralizec.zeta.org.au