Skip to content

Commit

Permalink
Make getenv thread-safe
Browse files Browse the repository at this point in the history
In order to return a non-owning pointer without memory leaks the
function needs to use a static variable.
When calling it from multiple threads there is a data race during the
assignment (and conversion) to this variable.
Fix by making it `thread_local`.

Fixes #189
  • Loading branch information
Flamefire committed Nov 29, 2024
1 parent 4a07829 commit ca7dfa7
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
7 changes: 6 additions & 1 deletion include/boost/nowide/cstdlib.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,12 @@ namespace nowide {
///
/// \brief UTF-8 aware getenv. Returns 0 if the variable is not set.
///
/// This function is not thread safe or reenterable as defined by the standard library
/// The string pointed to shall not be modified by the program.
/// This function is thread-safe as long as no other thread modifies the host environment.
/// However subsequent calls to this function might overwrite the string pointed to.
///
/// Warning: The returned pointer might only be valid for as long as the calling thread is alive.
/// So avoid passing it across thread boundaries.
///
BOOST_NOWIDE_DECL char* getenv(const char* key);

Expand Down
2 changes: 1 addition & 1 deletion src/cstdlib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ namespace boost {
namespace nowide {
char* getenv(const char* key)
{
static stackstring value;
thread_local stackstring value;

const wshort_stackstring name(key);

Expand Down

0 comments on commit ca7dfa7

Please sign in to comment.