fopen: allocate the dir after fopen

Move the allocation of the directory name down to after the fopen() call
to allow that shortcut code path to avoid a superfluous malloc+free
cycle.

Follow-up to 73b65e94f3

Closes #12398
This commit is contained in:
Daniel Stenberg 2023-11-24 09:46:32 +01:00
parent 5b65e7d1ae
commit f27b8dba73
No known key found for this signature in database
GPG key ID: 5CC908FDB71E12C2

View file

@ -99,18 +99,13 @@ CURLcode Curl_fopen(struct Curl_easy *data, const char *filename,
char *tempstore = NULL; char *tempstore = NULL;
struct_stat sb; struct_stat sb;
int fd = -1; int fd = -1;
char *dir; char *dir = NULL;
*tempname = NULL; *tempname = NULL;
dir = dirslash(filename);
if(!dir)
goto fail;
*fh = fopen(filename, FOPEN_WRITETEXT); *fh = fopen(filename, FOPEN_WRITETEXT);
if(!*fh) if(!*fh)
goto fail; goto fail;
if(fstat(fileno(*fh), &sb) == -1 || !S_ISREG(sb.st_mode)) { if(fstat(fileno(*fh), &sb) == -1 || !S_ISREG(sb.st_mode)) {
free(dir);
return CURLE_OK; return CURLE_OK;
} }
fclose(*fh); fclose(*fh);
@ -120,9 +115,14 @@ CURLcode Curl_fopen(struct Curl_easy *data, const char *filename,
if(result) if(result)
goto fail; goto fail;
/* The temp file name should not end up too long for the target file dir = dirslash(filename);
system */ if(dir) {
tempstore = aprintf("%s%s.tmp", dir, randbuf); /* The temp file name should not end up too long for the target file
system */
tempstore = aprintf("%s%s.tmp", dir, randbuf);
free(dir);
}
if(!tempstore) { if(!tempstore) {
result = CURLE_OUT_OF_MEMORY; result = CURLE_OUT_OF_MEMORY;
goto fail; goto fail;
@ -137,7 +137,6 @@ CURLcode Curl_fopen(struct Curl_easy *data, const char *filename,
if(!*fh) if(!*fh)
goto fail; goto fail;
free(dir);
*tempname = tempstore; *tempname = tempstore;
return CURLE_OK; return CURLE_OK;
@ -148,7 +147,6 @@ fail:
} }
free(tempstore); free(tempstore);
free(dir);
return result; return result;
} }