[libc][string] fix strncpy potential buffer overflow #389
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.