strndup bug [fix included]

David Carne davidcarne@gmail.com
Fri Feb 10 20:28:00 GMT 2006


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