[LTP] [PATCH v5] open: fix cleanup condition and use snprintf

Jinseok Kim always.starving0@gmail.com
Wed Mar 25 13:22:05 CET 2026


Replace sprintf() with snprintf() for safer string handling.

The cleanup logic checked '!first' to decide whether to close file
descriptors. Since file descriptor 0 is valid, this may incorrectly
skip cleanup and leak descriptors.

Also initialize "first" to -1 and set the fds array to -1 after
allocation. Skip such entries in cleanup() to avoid calling SAFE_CLOSE()
on invalid file descriptors.

Signed-off-by: Jinseok Kim <always.starving0@gmail.com>
---
 testcases/kernel/syscalls/open/open04.c | 24 ++++++++++++++----------
 1 file changed, 14 insertions(+), 10 deletions(-)

diff --git a/testcases/kernel/syscalls/open/open04.c b/testcases/kernel/syscalls/open/open04.c
index 7573af1c8..3457024fc 100644
--- a/testcases/kernel/syscalls/open/open04.c
+++ b/testcases/kernel/syscalls/open/open04.c
@@ -15,7 +15,8 @@

 #define FNAME "open04"

-static int fds_limit, first, i;
+static int fds_limit;
+static int first = -1;
 static int *fds;
 static char fname[20];

@@ -29,10 +30,11 @@ static void setup(void)
 	first = SAFE_OPEN(FNAME, O_RDWR | O_CREAT, 0777);

 	fds = SAFE_MALLOC(sizeof(int) * (fds_limit - first));
+	memset(fds, -1, sizeof(int) * (fds_limit - first));
 	fds[0] = first;

-	for (i = first + 1; i < fds_limit; i++) {
-		sprintf(fname, FNAME ".%d", i);
+	for (int i = first + 1; i < fds_limit; i++) {
+		snprintf(fname, sizeof(fname), FNAME ".%d", i);
 		fd = open(fname, O_RDWR | O_CREAT, 0777);
 		if (fd == -1) {
 			if (errno != EMFILE)
@@ -46,20 +48,22 @@ static void setup(void)

 static void run(void)
 {
-	sprintf(fname, FNAME ".%d", fds_limit);
+	snprintf(fname, sizeof(fname), FNAME ".%d", fds_limit);
 	TST_EXP_FAIL2(open(fname, O_RDWR | O_CREAT, 0777), EMFILE);
 }

 static void cleanup(void)
 {
-	if (!first || !fds)
-		return;
+	if (first >= 0) {
+		int limit = fds_limit - first;

-	for (i = first; i < fds_limit; i++)
-		SAFE_CLOSE(fds[i - first]);
+		for (int i = 0; i < limit; i++) {
+			if (fds[i] != -1)
+				SAFE_CLOSE(fds[i]);
+		}
+	}

-	if (fds)
-		free(fds);
+	free(fds);
 }

 static struct tst_test test = {
--
2.43.0


More information about the ltp mailing list