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.
The wrong placement of the increment for index
i
causes an unexpected behavior, which thestrncpy
writes an extra '\0'.For example: The
src
string is "abc". The buffer size ofdest
is 5.When we call
strncpy(dest, src, 5)
, the firstfor
loop copies the characters, 'a', 'b', and 'c', to thedest[0:2]
. In the 4th iteration, however, thefor
loop breaks due to the termination ofsrc
whereas the value ofi
stays 3. At the moment, it has copied 4 bytes, including the '\0' ofsrc
.In the second
for
loop, we havei = 3
andcount = 5
, so the loop copies two more '\0' to thedest
. As a result, thestrncpy
copies 6 bytes to thedest
buffer, leading to buffer overflow.Fix the issue by increasing the index
i
before every copy.