wm: teppich

Download patch

ref: 51f721af94855f73d8cebccb49d782f100fd3454
parent: becccca115f0f2c1f42f12fd891481bd8211eb44
author: mkf <mkf@cloud9p.org>
date: Thu Nov 30 07:20:37 EST 2023

strcntok, strncpy: simplify and fix bunch of bugs reported by de. (thanks de!)

strcntok: use strncpy instead of memcpy
strncpy: rewrite and simplify a bit

--- a/libc/strcntok.c
+++ b/libc/strcntok.c
@@ -8,7 +8,7 @@
 {
 	int i, b, match, lastmatch, lastnotmatch;
 	char *res;
-			
+
 	match = -1; /* n = 0, match++ = 0 */
 	lastmatch = 0;
 	i = 0;
@@ -19,24 +19,23 @@
 			match++;
 			if(match == n)
 			{
-				res = malloc(i + 1 - lastmatch); /* i - lastmatch + '\0' */
-				/* TODO: use strncpy */	
-				memcpy(res, src + lastmatch, i - lastmatch);
-				res[i - lastmatch] = '\0';
+				res = (char*)malloc(i + 1 - lastmatch); /* i - lastmatch + '\0' */
+				strncpy(res, src + lastmatch, i - lastmatch);
 				return res;
 			}
 
 			lastmatch = i+1;
 		}
+
 		i++;
 	}
 	
 	/* last instance would return anything left */
-	if(n == match + 1)
+	if(match == n - 1)
 	{
-		res = malloc(i - lastmatch);
-		memcpy(res, src + lastmatch, i - lastmatch);
-		return res;	
+		res = (char*)malloc(i + 1 - lastmatch);
+		strncpy(res, src + lastmatch, i - lastmatch);
+		return res;
 	}
 	return nil;
 }
--- a/libc/strncpy.c
+++ b/libc/strncpy.c
@@ -3,18 +3,16 @@
 char*
 strncpy(char *dst, const char *src, size_t num)
 {
-	char *dst_p = dst;
+	char *dst_p;
 
-	if (num != 0) {
-
-		do {
-			if ((*dst++ = *src++) == 0) {
-				/* NULL pad the remaining n-1 bytes */
-				while (--num != 0)
-					*dst++ = 0;
-				break;
-			}
-		} while (--num != 0);
+	dst_p = dst;
+	while(*src != '\0' && num > 0)
+	{
+		*dst++ = *src++;
+		num--;
 	}
+	if(src != '\0')
+		*dst = '\0';
+
 	return (dst_p);
 }