Skip to contentSkip to conversation

lib: string: reduce unnecessary loop in strncpy

PATCH In review Liu Xiang 2 participants 3 messages Oct 30, 2019 – Oct 31, 2019

Subsystems (2)
lore
Share & tools
lore

Liu Xiang

author
#0 lore raw

PATCH 1/1 lib: string: reduce unnecessary loop in strncpy

Now in strncpy, even src[0] is 0, loop will execute count times until count is 0. It is better to exit the loop immediately when *src is 0.

---
 lib/string.c | 8 ++------
 1 file changed, 2 insertions(+), 6 deletions(-)
lib/string.c +2 -6
index 08ec58c..1065352 100644
@@ -115,12 +115,8 @@ char *strncpy(char *dest, const char *src, size_t count)
 {
 	char *tmp = dest;
 
-	while (count) {
-		if ((*tmp = *src) != 0)
-			src++;
-		tmp++;
-		count--;
-	}
+	while (count-- && (*tmp++ = *src++) != '\0')
+		; /* nothing */
 	return dest;
 }
 EXPORT_SYMBOL(strncpy);
Signature · 1 line
1.9.1
#1 lore raw
Quoted 2 lines · Liu Xiang

Now in strncpy, even src[0] is 0, loop will execute count times until count is 0. It is better to exit the loop immediately when *src is 0.

Please read "man strncpy".

There's a reason the loop is written in that somewhat convoluted way:
The behavior of strncpy is mandated by the C standard, and if the src string is shorter than the destination buffer, the rest must be 0-filled. So if we hit a nul byte before running out of count, we keep copying that nul byte to the rest of the destination.

Rasmus

author
#2 lore raw
Quoted 6 lines · Rasmus Villemoes
Quoted 2 lines · Liu Xiang

Now in strncpy, even src[0] is 0, loop will execute count times until count is 0. It is better to exit the loop immediately when *src is 0.

Please read "man strncpy".

Quoted 7 lines

There's a reason the loop is written in that somewhat convoluted way:
The behavior of strncpy is mandated by the C standard, and if the src string is shorter than the destination buffer, the rest must be 0-filled. So if we hit a nul byte before running out of count, we keep copying that nul byte to the rest of the destination.

Rasmus

Hi Rasmus,

Thanks for your explanation. I ignored the C library standard.

Regards

Liu Xiang