Skip to content

Commit

Permalink
setup: Fix bug with strdup() of NULL pointer.
Browse files Browse the repository at this point in the history
getenv() can return NULL if the environment variable is not set, but
the result of getenv() was always being passed to M_StringDuplicate()
without any check. This could cause crashes on some platforms.
Instead, rework the code into a first stage that gets the player's
name and a second that duplicates it into a mutable form.

This fixes #455.
  • Loading branch information
fragglet committed Nov 4, 2014
1 parent 176050d commit 66b295d
Showing 1 changed file with 14 additions and 13 deletions.
27 changes: 14 additions & 13 deletions src/setup/multiplayer.c
Original file line number Diff line number Diff line change
Expand Up @@ -1059,28 +1059,29 @@ void SetPlayerNameDefault(void)
{
if (net_player_name == NULL)
{
net_player_name = M_StringDuplicate(getenv("USER"));
net_player_name = getenv("USER");
}

if (net_player_name == NULL)
{
net_player_name = M_StringDuplicate(getenv("USERNAME"));
net_player_name = getenv("USERNAME");
}

// On Windows, environment variables are in OEM codepage
// encoding, so convert to UTF8:

#ifdef _WIN32
if (net_player_name != NULL)
{
net_player_name = M_OEMToUTF8(net_player_name);
}
#endif

if (net_player_name == NULL)
{
net_player_name = M_StringDuplicate("player");
net_player_name = "player";
}

// Now strdup() the string so that it's in a mutable form
// that can be freed when the value changes.

#ifdef _WIN32
// On Windows, environment variables are in OEM codepage
// encoding, so convert to UTF8:
net_player_name = M_OEMToUTF8(net_player_name);
#else
net_player_name = M_StringDuplicate(net_player_name);
#endif
}

void MultiplayerConfig(void)
Expand Down

1 comment on commit 66b295d

@edward-san
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just giving my cent, what about moving this kind of code in an another function, like M_GetEnvString?

Please sign in to comment.