2
0
mirror of https://github.com/boostorg/nowide.git synced 2026-01-19 04:22:12 +00:00

Make getenv thread-safe

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
This commit is contained in:
Alexander Grund
2024-11-29 09:53:38 +01:00
committed by Alexander Grund
parent 1423d15ba5
commit 9646dc324d
2 changed files with 7 additions and 2 deletions

View File

@@ -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);

View File

@@ -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);