Skip to contentSkip to conversation

alpha: Replace sprintf()/strcpy() with scnprintf()/strscpy()

PATCH Superseded Thorsten Blum 2 participants 2 messages Apr 19, 2025 – Apr 20, 2025 Alpha port

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 alpha: Replace sprintf()/strcpy() with scnprintf()/strscpy()

Replace sprintf() with the safer variant scnprintf() and use its return value instead of calculating the string length again using strlen().

Use strscpy() instead of the deprecated strcpy().

No functional changes intended.

---
 arch/alpha/kernel/core_marvel.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)
arch/alpha/kernel/core_marvel.c +7 -4
index b1bfbd11980d..d38f4d6759e4 100644
@@ -17,6 +17,7 @@
 #include <linux/vmalloc.h>
 #include <linux/mc146818rtc.h>
 #include <linux/rtc.h>
+#include <linux/string.h>
 #include <linux/module.h>
 #include <linux/memblock.h>
 
@@ -79,10 +80,12 @@ mk_resource_name(int pe, int port, char *str)
 {
 	char tmp[80];
 	char *name;
-	
-	sprintf(tmp, "PCI %s PE %d PORT %d", str, pe, port);
-	name = memblock_alloc_or_panic(strlen(tmp) + 1, SMP_CACHE_BYTES);
-	strcpy(name, tmp);
+	size_t sz;
+
+	sz = scnprintf(tmp, sizeof(tmp), "PCI %s PE %d PORT %d", str, pe, port);
+	sz += 1; /* NUL terminator */
+	name = memblock_alloc_or_panic(sz, SMP_CACHE_BYTES);
+	strscpy(name, tmp, sz);
 
 	return name;
 }
Signature · 1 line
2.49.0
#1 lore raw
Quoted 4 lines · Thorsten Blum

Replace sprintf() with the safer variant scnprintf() and use its return value instead of calculating the string length again using strlen().

Use strscpy() instead of the deprecated strcpy().

FWIW, an idiomatic variant would be

	size = snprintf(NULL, 0, <....>);
	buffer = <allocate size + 1 bytes>
	if succeeded
		snprintf(buffer, size + 1, <....>);