Return to BSD News archive
Xref: sserve comp.os.386bsd.questions:11959 comp.os.386bsd.development:2360 comp.os.386bsd.misc:2955 Path: sserve!newshost.anu.edu.au!harbinger.cc.monash.edu.au!bunyip.cc.uq.oz.au!munnari.oz.au!spool.mu.edu!howland.reston.ans.net!gatech!swrinde!news.uh.edu!uuneo.neosoft.com!Starbase.NeoSoft.COM!nobody From: peter@Starbase.NeoSoft.COM (Peter da Silva) 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: 31 Jul 1994 14:53:05 -0500 Organization: NeoSoft Internet Services +1 713 684 5969 Lines: 32 Message-ID: <31gvf1$h19@Starbase.NeoSoft.COM> References: <30lrf3$2ii@acmez.gatech.edu> <31cf70$3c@Starbase.NeoSoft.COM> <jmonroyCts1rL.96o@netcom.com> <31f1v8$2lg@mozo.cc.purdue.edu> NNTP-Posting-Host: starbase.neosoft.com 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'; You're right. My original code was: > if(result = fgets(buf, sizeof(buf), stdin)) { char *tmp; > if(tmp = strchr(buf, '\n')) > *tmp = '\0'; } I managed to somehow convince myself that if result was nonzero, I was safe without the extra temporary. I can't imagine what I was thinking of. 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.