[LTP] [PATCH v4] open: fix cleanup condition and use snprintf
Jinseok Kim
always.starving0@gmail.com
Sat Mar 21 15:08:13 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 | 16 ++++++++++------
1 file changed, 10 insertions(+), 6 deletions(-)
diff --git a/testcases/kernel/syscalls/open/open04.c b/testcases/kernel/syscalls/open/open04.c
index 7573af1c8..78254d397 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, i;
+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);
+ snprintf(fname, sizeof(fname), FNAME ".%d", i);
fd = open(fname, O_RDWR | O_CREAT, 0777);
if (fd == -1) {
if (errno != EMFILE)
@@ -46,17 +48,19 @@ 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)
+ if (first < 0 || !fds)
return;
- for (i = first; i < fds_limit; i++)
- SAFE_CLOSE(fds[i - first]);
+ for (i = first; i < fds_limit; i++) {
+ if (fds[i - first] != -1)
+ SAFE_CLOSE(fds[i - first]);
+ }
if (fds)
free(fds);
--
2.43.0
More information about the ltp
mailing list