From 66ce00153bd35bb83a296f7eb31efec6d6e6768b Mon Sep 17 00:00:00 2001 From: Lukas Fleischer Date: Mon, 21 Jul 2014 22:56:37 +0200 Subject: Refactor new_tempfile() Avoid preallocating buffers on the stack, use dynamic memory allocation instead. Also, change the semantics of new_tempfile() so that it returns the full name of the temporary file and fix all call sites. Signed-off-by: Lukas Fleischer --- src/utils.c | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) (limited to 'src/utils.c') diff --git a/src/utils.c b/src/utils.c index 34bdd5e..527dec8 100644 --- a/src/utils.c +++ b/src/utils.c @@ -619,21 +619,16 @@ const char *get_tempdir(void) * Create a new unique file, and return a newly allocated string which contains * the random part of the file name. */ -char *new_tempfile(const char *prefix, int trailing_len) +char *new_tempfile(const char *prefix) { - char fullname[BUFSIZ]; - int prefix_len, fd; + char *fullname; + int fd; FILE *file; if (prefix == NULL) return NULL; - prefix_len = strlen(prefix); - if (prefix_len + trailing_len >= BUFSIZ) - return NULL; - memcpy(fullname, prefix, prefix_len); - memset(fullname + prefix_len, 'X', trailing_len); - fullname[prefix_len + trailing_len] = '\0'; + asprintf(&fullname, "%s.XXXXXX", prefix); if ((fd = mkstemp(fullname)) == -1 || (file = fdopen(fd, "w+")) == NULL) { if (fd != -1) { @@ -642,11 +637,13 @@ char *new_tempfile(const char *prefix, int trailing_len) } ERROR_MSG(_("temporary file \"%s\" could not be created"), fullname); + + mem_free(fullname); return NULL; } fclose(file); - return mem_strdup(fullname + prefix_len); + return fullname; } /* -- cgit v1.2.3-54-g00ecf