[libc][string] fix strncpy potential buffer overflow
The wrong placement of the increment for index `i` causes an unexpected behavior, which the `strncpy` writes an extra '\0'. For example: The `src` string is "abc". The buffer size of `dest` is 5. When we call `strncpy(dest, src, 5)`, the first `for` loop copies the characters, 'a', 'b', and 'c', to the `dest[0:2]`. In the 4th iteration, however, the `for` loop breaks due to the termination of `src` whereas the value of `i` stays 3. At the moment, it has copied 4 bytes, including the '\0' of `src`. In the second `for` loop, we have `i = 3` and `count = 5`, so the loop copies two more '\0' to the `dest`. As a result, the `strncpy` copies 6 bytes to the `dest` buffer, leading to buffer overflow. Fix the issue by increasing the index `i` before every copy. Signed-off-by: Cody Wong <codycswong@google.com>
This commit is contained in:
committed by
Travis Geiselbrecht
parent
ec261bcf45
commit
94a15119b2
@@ -17,7 +17,7 @@ strncpy(char *dest, char const *src, size_t count) {
|
||||
char *tmp = dest;
|
||||
|
||||
size_t i;
|
||||
for (i = 0; i < count && (*dest++ = *src++) != '\0'; i++)
|
||||
for (i = 0; i++ < count && (*dest++ = *src++) != '\0'; )
|
||||
;
|
||||
for (; i < count; i++)
|
||||
*dest++ = '\0';
|
||||
|
||||
Reference in New Issue
Block a user