Skip to content

Commit 9cb46a2

Browse files
Correct string length handling in strlimcpy in halcmd.c
The strlen value is the string length, often fetched from strlen(), which return the number of characters in the string, excluding the terminal NUL character. To have room to copy the string into *dest, the *destspace available must be strlen+1, not strlen, to also have room for the NUL at the end. Setting NUL explicitly will not be needed in the case srclen reflect the real length of str, but if srclen is smaller than the real length of str, will will ensure the string is always NUL terminated. Pass *destspace instead of strlen+1 to strncpy() ensure the actual target size limit is used no matter what the content of srclen is.
1 parent 973ecc3 commit 9cb46a2

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

src/hal/utils/halcmd.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -678,10 +678,10 @@ static int strip_comments ( char *buf )
678678
679679
*/
680680
static int strlimcpy(char **dest, char *src, int srclen, int *destspace) {
681-
if (*destspace < srclen) {
681+
if (*destspace < srclen+1) {
682682
return -1;
683683
} else {
684-
strncpy(*dest, src, srclen);
684+
strncpy(*dest, src, *destspace);
685685
(*dest)[srclen] = '\0';
686686
srclen = strlen(*dest); /* use the actual number of bytes copied */
687687
*destspace -= srclen;

0 commit comments

Comments
 (0)