Re: Escaping white space in an NSString
Re: Escaping white space in an NSString
- Subject: Re: Escaping white space in an NSString
- From: Greg Guerin <email@hidden>
- Date: Thu, 21 May 2009 10:10:19 -0700
Bruce Johnson wrote:
char mdfile[PATHSIZE];
strncpy(mdfile, <pathToFile>, MAXREAD);
FILE * stream = fopen(<pathToFile>, "rt");
On further reflection, this code fragment looks very suspicious.
First, a local char buffer of length PATHSIZE is declared. We don't
know what PATHSIZE is.
Second, some unknown variable is copied into that buffer, but the
length is declared as MAXREAD, when it really ought to be PATHSIZE.
Since we don't know MAXREAD's magnitude relative to PATHSIZE, nor do
we know what <pathToFile> really is, this could cause a buffer
overflow. Equally bad, if MAXREAD is less than the strlen of
<pathToFile>, strncpy() will not put a NUL terminator on the copied
data, and subsequent calls that expect a nul-terminated C string
(viz. fopen()) will not do the right thing.
A typical idiom for using strncpy() with buffers whose length is
known is:
strncpy( dstBuf, srcBuf, sizeof(dstBuf) );
Note this idiom only works when dstBuf is declared as an array of
definite length. It won't work when dstBuf is a pointer expression.
Third, the 'mdfile' buffer that just received a copy of <pathToFile>
is now ignored, and the original <pathToFile> is used as the filename
to fopen(). So what was the purpose of mdfile and the strncpy()
anyway? If mdfile is used later, why copy <pathToFile> into it? If
mdfile isn't used later, why have it at all?
Fourth, the second arg to fopen is "rt". However, the man page for
fopen shows no significant for the 't' character. Optional 'b' or
'x', yes, but no 't'.
There is a '+' character recognized by fopen(), and '+' looks
somewhat like 't', but that's the only explanation I can imagine for
what "rt" might have been intended to mean. If that was the intent,
it's wrong. If that wasn't the intent, then an explanation for 't'
might be useful.
http://developer.apple.com/documentation/Darwin/Reference/Manpages/
man3/fopen.3.html
-- GG
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden