Clean up system_default_filename()

In the old implementation there were two static C-style strings, filename
and path, which were initialized to NULL and filled on first call of
the function (i.e. singletons).

There is no sense in having two static variables indicating whether
this function was called previously. Moreover, there is no point
in remembering filename accross function calls, because it is not
used once path is set to a non-NULL value.

Therefore, make the filename variable non-static and calculate it only on
first invocation (as indicated by a NULL path). Moreover, free() the filename
variable after its use to fix a memory leak of the old code.

The windows code is slightly different in that the temporary filename is
not dynamically allocated.

Signed-off-by: Berthold Stoeger <bstoeger@mail.tuwien.ac.at>
This commit is contained in:
Berthold Stoeger 2017-11-18 10:55:01 +01:00 committed by Lubomir I. Ivanov
parent 7a99d7e5c3
commit 04f38d61d7
3 changed files with 14 additions and 17 deletions

View file

@ -83,18 +83,17 @@ const char *system_default_directory(void)
const char *system_default_filename(void)
{
static char *filename = NULL;
if (!filename) {
static const char *path = NULL;
if (!path) {
const char *user = getenv("LOGNAME");
if (same_string(user, ""))
user = "username";
filename = calloc(strlen(user) + 5, 1);
char *filename = calloc(strlen(user) + 5, 1);
strcat(filename, user);
strcat(filename, ".xml");
}
static const char *path = NULL;
if (!path)
path = system_default_path_append(filename);
free(filename);
}
return path;
}

View file

@ -81,18 +81,17 @@ const char *system_default_directory(void)
const char *system_default_filename(void)
{
static char *filename = NULL;
if (!filename) {
static const char *path = NULL;
if (!path) {
const char *user = getenv("LOGNAME");
if (same_string(user, ""))
user = "username";
filename = calloc(strlen(user) + 5, 1);
char *filename = calloc(strlen(user) + 5, 1);
strcat(filename, user);
strcat(filename, ".xml");
}
static const char *path = NULL;
if (!path)
path = system_default_path_append(filename);
free(filename);
}
return path;
}

View file

@ -103,17 +103,16 @@ const char *system_default_directory(void)
*/
const char *system_default_filename(void)
{
static wchar_t filename[UNLEN + 5] = { 0 };
if (!*filename) {
static const char *path = NULL;
if (!path) {
wchar_t username[UNLEN + 1] = { 0 };
DWORD username_len = UNLEN + 1;
GetUserNameW(username, &username_len);
wchar_t filename[UNLEN + 5] = { 0 };
wcscat(filename, username);
wcscat(filename, L".xml");
}
static const char *path = NULL;
if (!path)
path = system_default_path_append(filename);
}
return path;
}