strndup bug [fix included]

Jeff Johnston jjohnstn@redhat.com
Mon Feb 13 17:33:00 GMT 2006


Thanks David.  Fixes have been checked in.  The logic in strnlen needed 
tweaking because it was looking for the nul terminator before checking 
the max limit so one could end up getting an access failure, even though 
the n value should have stopped it from happening.

-- Jeff J.

David Carne wrote:
> Issue:
> strndup crashes [sometimes] when presented with a non-null terminated
> source string, even if the length parameter is within the bounds of
> the source string.
> 
> The problem is caused by:
> size_t len = MIN(strlen (str), n); [Line 13, newlib/libc/string/strndup_r.c]
> 
> The strlen will attempt to measure the length of the entire string
> before comparison with the length parameter, which is not only
> inefficient, but causes the bug noted above ;).
> 
> The fix is to replace strlen (str) with strnlen(str, n) - and since
> the MIN then becomes irrelevant, line 13 could be replaced with
> 
> size_t len = strnlen (str, n);
> 
> Cheers,
> 
> --David Carne



More information about the Newlib mailing list