Re: _FORTIFY_SOURCE and strncat(), buggy?
Re: _FORTIFY_SOURCE and strncat(), buggy?
- Subject: Re: _FORTIFY_SOURCE and strncat(), buggy?
- From: Greg Guerin <email@hidden>
- Date: Thu, 24 Jul 2008 13:45:40 -0700
Sean McBride wrote:
size_t size = 50;
char* buffer = (char*)calloc(size, 1);
// buffer[0] = 'q'; // uncomment this to 'fix'.
strncat(buffer, "test", (size-1));
Seems slightly wrong to me. I think strncat's 3rd arg should be size-2.
More precisely, it should be:
size - strlen(buffer) - 1
Referring to its man page; strncat() will append up to 'count' chars
from the 2nd string, then append a NUL. That is, it may append up to
'count+1' chars to the 1st string. However, the only time that would
work with a count of size-1, given an arbitrary 2nd string and a
buffer 50 bytes long, is when buffer[0] is NUL, i.e. when strlen
(buffer) is 0. Work it out by hand and it'll be clearer.
I have no idea how this relates to _FORTIFY_SOURCE, I'm just saying
it seems wrong in the general case of the 2nd arg. Obviously, in
this specific case, "test" is constant and much less than 50 bytes
long, which clearly should work. Worse, putting 'q' in buffer[0]
should cause a buffer overflow (make it fail) in the general case,
not fix it and make it work.
According to this:
http://gcc.gnu.org/ml/gcc-patches/2004-09/msg02055.html
"With -D_FORTIFY_SOURCE=2 some more checking is added, but
some conforming programs might fail."
Google for strncat and _FORTIFY_SOURCE to see if others have seen
similar problems. Or use strlcat().
-- GG
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden