r/cpp • • Jun 04 '26

PSA - Do not assign the result of `::getenv` to a `std::string`

This is a lesson I apparently have to learn repeatedly. Many, many times. Way too many times.

Unit tests are failing, I'm too ADD to actually read the error message for comprehension, fart around changing things to try to find why the exception is being thrown, then spontaneously remember "oh, yeah, ::getenv will return NULL if the variable hasn't been defined, and assigning a NULL to a std::string is Bad Juju.

Wasted a whole day on this nonsense.

I know this. I have known this for years, and I still make this mistake.

Blah. Needed to vent.

Edit: Since this question has come up, no, I couldn't run it in a debugger. This was an automated build running under Jenkins following a push to Bitbucket, so all I had to go by was output from the build script and test harness. An uncaught exception was being thrown and the message said that NULL was not allowed in a string constructor, but no information as to where it was happening.

I couldn't reproduce the issue on the dev system because all the environment variables were defined there, so it took a while to put two and two together.

215 Upvotes

118 comments sorted by

17

u/bitzap_sr Jun 05 '26 edited Jun 05 '26

WTH did it take you a day to figure this out? didn't you run the thing under a debugger?

8

u/SmokeMuch7356 Jun 05 '26

Couldn't run it in a debugger. This was an automated build running under Jenkins following a push to Bitbucket, and all I had was the build and unit test output to go by. An uncaught exception was being thrown in the test harness and there was an error message telling me that NULL was an invalid constructor for a std::string, but it wasn't telling me exactly where that was happening.

It wasn't reproducing on the dev system because those variables were defined there, so it took me a while before I made the connection.

It's a mistake I can't stop making for some reason. It's bitten me in the ass before. I get lazy/distracted/whatever and write stupid shit.

Again, I just needed to vent.

6

u/max123246 Jun 05 '26

Beauty of undefined behavior. Makes the simplest bugs eclectic and non local. Though yeah, probably just wasn't a bug they noticed until they started using the function and had written a bunch of other code

4

u/StaticCoder Jun 05 '26

string throws an exception in that case, at least with gcc. This is supremely annoying as that doesn't get a backtrace, while a null deref does in my system.

3

u/bitzap_sr Jun 05 '26

"catch throw" in gdb exists.

3

u/StaticCoder Jun 05 '26

Unfortunately my software doesn't run under gdb in production.

7

u/saxbophone mutable volatile void Jun 05 '26

Maybe you should actually read the error messages next time

3

u/SmokeMuch7356 Jun 05 '26 edited Jun 05 '26

Yup. Again, ADD. And a desperate desire to be working on something, anything else. I just want to see the back of this goddamned thing for good.

2

u/saxbophone mutable volatile void Jun 05 '26

No shame, I understand the feeling —tunnel vision. I just find that it helps (sometimes, I haven't yet seen a compiler that gives truly readable template error messages).

10

u/tim_pipperton Jun 04 '26

Shouldn’t they be a (potentially const) string_view?

8

u/SmokeMuch7356 Jun 04 '26

Shouldn't what be a string_view?  

getenv returns char *; that's the problem. 

17

u/sultan_hogbo Jun 04 '26

Never assign null to a string_view. It doesn’t expect that.

11

u/mereel Jun 05 '26

This is exactly the kind of thing that's convinced me that C++ was a mistake. If a function accepts a raw pointer, it better handle a null pointer as well.

→ More replies (3)

5

u/fdwr fdwr@github 🔍 Jun 04 '26

Are there interesting cases where it's useful to know whether an environment variable is undefined vs defined but as explicitly ""? For example in C#, you can say Environment.SetEnvironmentVariable("TEST", string.Empty) which sets it to an empty value, vs Environment.SetEnvironmentVariable("TEST", null) which deletes the variable. If so, std::string_view would be ambiguous, whereas std::optional<std::string_view> would be unambiguous.

4

u/rdtsc Jun 05 '26

If so, std::string_view would be ambiguous

A zero-length string_view can either contain a nullptr or not.

2

u/fdwr fdwr@github 🔍 Jun 05 '26

🤔 True. The pointer must be nonnull if you have a nonzero length, and the single parameter constructor rejects null pointers (basic_string_view(std::nullptr_t) = delete), but for the explicit overload, nullptr appears allowed for zero length (std::string_view{nullptr, 0}). So I suppose you could distinguish between data() being nullptr vs pointing to a valid but empty literal "".

4

u/thefool-0 Jun 05 '26

This is true for any function returning a pointer unless you are very confident it will never be null (or that your code using it will degrade or crash in a helpful way if it is null). Why is it so surprising? 

1

u/SmokeMuch7356 Jun 05 '26

It's not surprising. It's just a mistake I can't stop making for some reason. I needed to vent after doing it to myself again for the millionth time.

123

u/No-Dentist-1645 Jun 05 '26 edited Jun 05 '26

I always use this short wrapper function:

std::optional<std::string> get_env(const char *name) {
  const char *val = std::getenv(name);
  if (val == nullptr) {
    return std::nullopt;
  }
  return std::string(val);
}

It lets me do cool functional composition such as:

LogLevel level = get_env("LOGLEVEL")
                  .and_then(from_chars<std::underlying_type_t<LogLevel>>)
                  .transform([](auto val) -> LogLevel {
                    return LogLevel(
                        std::clamp(val, std::to_underlying(LogLevel::NONE),
                                   std::to_underlying(LogLevel::ALL)));
                  })
                  .value_or(LogLevel::INFO);

20

u/azswcowboy Jun 05 '26

That’s a really nice approach that highlights a cool composition of more recent features.

7

u/markuspeloquin Jun 05 '26

How do you feel about differentiating empty and undefined env variables? Generally they seem to be treated the same, and in some contexts, it's impossible to unset them (I recall it was something related to docker). So as a rule, I don't differentiate them.

7

u/dustyhome Jun 05 '26

That depends on the application, and wether an empty string is a valid value with a distinct behavior.

2

u/markuspeloquin Jun 05 '26

Well seeing as it's sometimes impossible to unset them, you probably need some other way to differentiate them.

In general, I've been convinced that null/missing/empty should all be treated the same.

1

u/bwmat Jun 06 '26

Env vars can't be null... Can they? 

6

u/markuspeloquin Jun 06 '26

They can be absent and they can be empty.

→ More replies (2)

2

u/No-Dentist-1645 Jun 05 '26

I usually don't differentiate them either, I haven't yet ran into a scenario where I wanted to specialize set-but-empty environment variables as anything but exactly like unset

4

u/Ryotian Jun 05 '26

Awesome idea I will be stealing this trick. That code style looks incredibly clean imo

2

u/alex-weej Jun 05 '26

Independently I do the same thing, exactly. Wish it was std::!

3

u/BigTanuki64 Jun 05 '26

Why `char const*` instead of `std::string_view`?

13

u/No-Dentist-1645 Jun 05 '26

std::getenv is basically a wrapper for the posix getenv, which takes a null-terminated char pointer.

Generally, you should not use std::string_view when you're calling external C functions that expect a null-terminated char*. It has zero guarantees about being null-terminated, so if you wanted to pass it, you'd have to explicitly check that it's null terminated, and if not, copy it to a string then use that. This "requirement" is also explicit in the language, it's why std::string (which is null terminated) has a .c_str() method that will return a valud C string, while std::string_view only has a .data() that just returns the pointer to the data, no null-terminated guarantees. On the other hand, a const char* when it refers to a string and not just a random pointer to some char is generally agreed to always be null-terminated by universal convention.

This is also why some standard classes like std::ofstream only accept either const char* or const std::string& for their constructors, because they internally call OS functions like fopen which expect null-termination.

There is a C++29 proposal for a std::cstring_view, which is the same as a string view except that it does guarantee it's null terminated, but until then you should avoid regular string views for such purposes.

1

u/shachark Jun 05 '26

The composition is cool, but I personally will prefer separating the description of the environment variable from actually getting it as part of my aversion to globally accessing things and singletons.

won't really write it like that, but for the sake of making the point something like that:
Environment<LogLevel> getLogLevel = [](GetEnvFunc get_env) { return get_env("LOGLEVEL")...; };

and explicitly invoke it in "legitimate" places.

To incentivize making environment accessing code slightly more explicit. WDYT?

2

u/No-Dentist-1645 Jun 05 '26

That's an interesting approach and I definitely see scenarios where it could be useful to have it designed like that, but I think that is something that depends on your specific use case and how often/in what matter you're accessing the environment.

For my use cases, we usually treat environment variables as "config parameters", under the assumption that they are set once and then the program is called, e.g LOGLEVEL=5 SANDBOXED=yes ./program, we are not actively modifying and watching for changes in the environment. LogLevel level is just a data member of the Logger class, we only care about the value of LOGLEVEL at the specific point where we initialize the logger. For that reason, level is only initialized at the Logger constructor, after which it never changes. That's why it makes sense to describe how we're getting the level directly on the constructor.

Your approach would make more sense in situations where you're actively writing and re-reading the environment on multiple places in your code, and you expect the environment variable to be able to change since the last time you fetched it.

→ More replies (1)

0

u/max0x7ba https://github.com/max0x7ba Jun 07 '26 edited Jun 07 '26

Writing C++ code is the most expensive in terms of time and labour cost. The expense is only worth paying for the ultimately fastest run-time performance, unachievable with any other cheaper-to-develop-with language.

Replacing nullptr return value of std::getenv with a default value string (literal) costs extra 2 CPU instructions (test and cmov).

Copying that char const* into std::string costs extra 64 CPU instructions, which include calls to strlen, operator new, memcpy, std::__throw_logic_error.

Replacing nullptr return value of std::getenv with std::optional<std::string>(), and std::optional<std::string>(val) otherwise, costs extra 117 CPU instructions, which include calls to strlen, operator new, memcpy, std::__throw_logic_error, with additional instructions for inlined std::optional constructor to copy/move its initializer.

Using std::optional requires paying high extra costs of more verbose code, slower compile time, larger machine code size, slower run-time performance. See https://godbolt.org/z/ahbKG7nao


std::optional looks like a neat concept in a textbook. But using it makes everything slower, larger, less efficient and more expensive; defeating the purpose of coding C++ for ultimate run-time efficiency in the first place.

Good engineering minimizes costs. std::optional only ever introduces high costs, which is the opposite of good engineering.

4

u/No-Dentist-1645 Jun 07 '26 edited Jun 07 '26

Writing C++ code is the most expensive in terms of time and labour cost. The expense is only worth paying for the ultimately fastest run-time performance, unachievable with any other cheaper-to-develop-with language.

This is not an "absolute truth", your comment makes it sound like if people should never use std::string because it "adds CPU instructions", but clearly that's not all there is. C++ is a "multi-paradigm programming language", it has many uses besides just "hyperfocus on performance and absolutely nothing else". Your programming style should be tailored to the exact purpose of the code you're writing. If you're doing ultra-low-level kernel development or embedded programming, then yes, you should probably care about how every function compiles down to the individual instruction. But that's not what all of us are doing, otherwise Python and Javascript wouldn't exist.

I mostly work on backend data processing for a SAAS company. We process some data and store the results, using a mix of Python and C++ depending on the exact objective. We can tolerate not having absolutely perfect CPU instructions since we do not have to present results immediately (they are used in the long term), but what we absolutely cannot have is our program crashing in the middle of a request and risk data being lost. That's why we have a C++ writing style that you may dislike due to the "inefficiencies", which include explicit error handling via std::optional and std::expected, as well as exceptions if necessary. Data processing should be composable so we can visualize the effects of every step and how to handle them.

Of course we still care about performance. But there is a strong incentive not to do "premature optimizations". "Good engineering" for us means write safe and failure-proof code first and foremost, analyze hot paths and optimize bottlenecks once you have your code working. Getting an environment variable has never been a hot path operation so far, we mostly just get them once at the program init and never in a loop. If it would be though, I would not use the helper function

→ More replies (9)

9

u/Tidemor Jun 04 '26

That title is a bit misleading tho, don't you think?

3

u/SmokeMuch7356 Jun 04 '26

No?

5

u/Questioning-Zyxxel Jun 05 '26

The title could include a "directly". Because you need to examine the return value before deciding if the result can be assigned.

4

u/SmokeMuch7356 Jun 05 '26

Hence, "do not assign the result of ::getenv to a std::string."

i.e., don't do

std::string str = ::getenv("FOO");

Figured that was clear enough.

4

u/biowpn Jun 05 '26

It is perfectly fine to assign the result of getenv to std::string, after checking it's not null.

The title should be "Do not directly assign the result of ::getenv to a std::string".

→ More replies (1)

47

u/TSP-FriendlyFire Jun 05 '26

Sounds to me like you need to make a wrapper returning a std::optional<std::string_view> and always use that.

If only we could modernize the STL...

46

u/OrphisFlo I like build tools Jun 05 '26

The environment is mutable and your string_view could point to something that is updated under you.

Technically, getenv is inherently racy, it's not a great API.

14

u/azswcowboy Jun 05 '26

This api needs to be fixed. There are earlier proposals that probably weren’t the best, but one should be forthcoming soon for c++29. I’ll post here when there’s news.

0

u/TSP-FriendlyFire Jun 05 '26

Unfortunately it's not easy to encode "you can use this view if it's transient, but copy it to a string if it's meant for long term storage" in the C++ type system. IMO, always copying into a std::string on the off chance the environment gets modified from under you is typically an unnecessary pessimization, though I suppose you shouldn't be getting an environment variable in your hot path in the first place.

14

u/StaticCoder Jun 05 '26

Indeed one could argue not using a string is premature optimization.

→ More replies (2)

5

u/OrphisFlo I like build tools Jun 05 '26

Itf you rely on the environment in your program, it's probably fine to wrap it in an object that will make a copy of it and adequately wraps setenv call.

The risk is that you have libraries that may call setenv under you and won't use that object. Calling getenv in a library is unfortunately common enough, and a bit crazy to do so, but we can't really change behavior now.

At least, if the goal is to change the environment of child processes, you don't need to change your own environment and there are ok APIs that allow for that.

2

u/evaned Jun 06 '26

always copying into a std::string on the off chance the environment gets modified from under you is typically an unnecessary pessimization

IMO, there are two reasonable designs for this function: optional<const char*> and optional<string>. Your suggestion of optional<string_view> IMO is at a bad middle ground, not a good middle ground. And then the first one IMO is out as well -- it should just return const char*, and then... do you need your function at all?

If you want your function to be safer even if the environment is modified later (as discussed in other comments, it's still far from safe in a multithreaded context), then you need string as discussed already.

You talk about that being unnecessary pessimization -- but there's also an unnecessary pessimization with string_view because it will need to call strlen to determine the length. Checking an environment variable for "set or not" doesn't require looking at any data, and checking "set-to-nonempty or not" requires only looking at the first byte of data. Those are both very common uses for envvars, and in both of them computing the length is a pessimization. So if you want your interface function to not add theoretically-arbitrary unnecessary overhead over the underlying call, you "need to" return a char*.

string_view misses out on both benefits and comes with both drawbacks. Admittedly the perf hit of that length is less than a string allocation, but I still think string_view is a bad middle ground.

1

u/bwmat Jun 06 '26

IMO getenv should take a callback where it passes the value, which is only valid until the callback returns

Then the impl. can implement the necessary locking to make it all work (I'd make it so setting new values doesn't block simply because there's callbacks in progress) 

3

u/ihsgyy Jun 05 '26

Cant return string view because any call to setenv will invalidate the ptr returned by getenv

58

u/Healthy-Act3539 Jun 04 '26 edited Jun 04 '26

This is how I usually do it:

char* var = std::getenv("MY_VAR");
if (var && *var != '\0') {
    // ...
}

Checks both if the variable exists and is not empty. Works well enough.

69

u/Electronic_Tap_8052 Jun 05 '26 edited Jun 05 '26

for those of us with some dignity

if (const auto var = std::getenv("MY_VAR") ; var){
    const std::string envString = var;
}

57

u/ludonarrator Jun 05 '26

Pedant mode: ; var isn't required here, and const auto* var would be more appropriate.

17

u/Electronic_Tap_8052 Jun 05 '26

gah, you're right. i dunno why i did that. I use it that way all the time.

that's what I get for trying to flex to strangers on the internet

8

u/friedkeenan Jun 05 '26

Maybe it's because I've worked too much with generic ranges/iterator code, but nowadays I actually find myself mildly preferring const auto ptr to const auto *ptr. Though it does make me wonder if I'm just going crazy

8

u/T-Lecom Jun 05 '26

I hope you do realise that they are not the same? const auto *ptr only protects the content behind the pointer, whereas const auto ptr only protects the pointer itself but not the contents behind it. What you usually want is auto const*const ptr to protect both.

→ More replies (1)

2

u/thisismyfavoritename Jun 05 '26

why?

2

u/friedkeenan Jun 05 '26

Well, with iterators there is not really an equivalent way to do auto *ptr = ... besides maybe like, std::input_iterator auto it = ... or something, but I don't really find that beneficial, and it certainly won't affect whether you can mutate the element that the iterator is pointing to, like one can with const auto *.

But of course you still will use all the pointer-y operators on iterators (and pointers can be used as iterators), so I guess it's kind of led to pointers not being all that special in my mind. And I maybe kinda think it's more valuable to have the actual pointer be const instead of the pointed-to element, and having both be const with const auto * const just looks bad.

But it is definitely flimsy reasoning. In the vast majority of cases though the name and the surrounding context make it clear what sort of thing the declared variable is, at least as much as auto does normally I think.

5

u/jonathancast Jun 05 '26

But then var is mutable /s

13

u/13steinj Jun 05 '26

Use a std::string_view, there's no need to allocate here.

9

u/guepier Bioinformatican Jun 05 '26

Oh but there is (in most cases), since std::getenv gives absolutely no guarantee that the contents behind the pointer couldn’t suddenly change (in particular, a different thread in the same process is allowed to directly modify the global environ variable on a POSIX-compliant system).

In other words, the following is not guaranteed!

setenv("FOO", "value", 1);
auto const foo = std::string_view(std::getenv("FOO"));
assert(foo == "value");

2

u/arghness Jun 05 '26

Technically, I think any call to putenv/setenv etc. in another thread is allowed to invalidate that pointer, to the extent that you can't even guarantee copying the value to a string is valid, without a mutex across all threads that may access the environment, as the pointer may be invalidated after the getenv and before copying to the string?

Before C++11, calls to getenv were also allowed to invalidate it.

2

u/13steinj Jun 05 '26

Sure, but this is true of the string view of any underlying data in the application. I take a view to some data. Multiple threads can write the data. View can be invalidated.

I'd argue though that you shouldn't pre-protect yourself against bad code.

16

u/dr_death47 Jun 05 '26

For those with even more dignity:

Hey Claude, get "MY_VAR" from env

/s

25

u/Healthy-Act3539 Jun 05 '26

You missed the obligatory "Make no mistakes" clause. Rookie mistake, smh my head.

1

u/wigglyworm91 Jun 05 '26

hot take, if it's set and empty then that should be an error condition, not a fallback

8

u/StaticCoder Jun 05 '26

Unsetting an environment variable can be difficult. I believe it's good practice to consider empty the same as unset.

5

u/markuspeloquin Jun 05 '26

One instance I ran into is that docker lets you override an environment variable defined in an image, but not unset it.

It's similar to passing variables on the command line, like CC=clang make. If my environment already has CC, the only way I can similarly clear it is CC= make. Or maybe (unset CC; make).

12

u/BitOBear Jun 05 '26

Do not assign the result of getenv to a string until you verified that the result is not null

There's a difference between a no result which tells you that there is no such environment variable, and a zero length result which tells you that the environment variable exists but has a value of a zero length string.

Since it's a stable pointer directly into the environment space of the process you can assign it temporarily to a variable and examine it before deciding whether to use it or not.

14

u/usefulcat Jun 05 '26 edited Jun 05 '26

When dealing with C APIs, I prefer to deal with problems like this once, as opposed to repeatedly:

std::string get_env(const char* name) {
    std::string s;
    if (name) {
        const char* p = getenv(name);
        if (p) {
            s = p;
        }
    }
    return s;
}

-1

u/max123246 Jun 05 '26

Why not a string view or reference to a string, why is name a pointer? Seems like a pretty unnecessary null check when you can encode it in the type

9

u/AVeryLazy Jun 05 '26

Please correct me if I'm wrong, but string views have no guarantee of a null terminator.. when you are calling a C function, this is a trap..

2

u/StaticCoder Jun 05 '26

I'm on a quest to replace const char * with string_view in my codebase, but some external APIs indeed require a NUL terminator which string_view cannot provide. Typically though those are expensive enough that allocating a string to call them is not an issue. There's no obvious conversion from string_view to const char * though so nul termination accidents are unlikely.

1

u/usefulcat Jun 05 '26 edited Jun 05 '26

You could also do something like this, which would often avoid the need to use a temporary std::string just for null termination.

3

u/max123246 Jun 05 '26

I mean a char* has no guarantee of a null terminator either

3

u/AVeryLazy Jun 05 '26

You have a point. But it's easier to obtain a substring from a string view than from another stringview than from a const char*. Both can be misused, but I'm working with a huge codebase that is also maintained by c# devs that don't know or care about c++, and I'm always trying to find the type that is least likely to be abused... But as always, they always find a way.

2

u/evaned Jun 06 '26

I think there's a pretty good counterargument to that, which is that while there's no guarantee, there is a very strong convention. If you see a const char* and (1) have reason to believe that it's a string and not a single character and (2) it's not paired with a length, I would say it's almost certain to be null-terminated (or at least intended as such).

Now I say this with caution because I was away from C++ programming for several years and only recently got back to it on a code base that uses a very C-like style, but my take of string_view is that there's no such convention -- if anything, there's a convention the other way that you can't rely on it being null-terminated.

One could imagine a custom string class that (very reasonably) has an implicit conversion into a string_view -- as std::string does -- but unlike std::string-in-practice doesn't keep the null-terminator around. Congrats, you just made an API that is very easy to mis-use, because you can say get_env(my_string) and have everything explode only at runtime. Assuming that your string class has a vaguely reasonable API, with a char* you'd need to explicitly do something to get it into a null-terminated form in order to call the char* version of the function.

Finally, comment above about the unnecessary null check. But string_view, you're doing an unnecessary strlen on anything that isn't a string literal in the source. That'll very probably be rather more costly.

1

u/usefulcat Jun 05 '26

As others have pointed out, std::string_view does not guarantee null termination, which getenv() requires.

If name were a string reference, that would force callers to construct a string if they don't already have one. I'd say adding an overload that accepts a string reference would be better.

From a c++ perspective, ideally getenv() would accept a string_view, but that's not the world we live in..

5

u/_Noreturn Jun 05 '26

This is why you make a wrapper I make a GetEnv<std::string>("Name") template, same for GetEnv<int>()

3

u/Infamous-Bed-7535 Jun 05 '26

Sorry to hear, but please use a debugger it will stop right where it throws, crashes. Spending a whole day on it :/

3

u/bartmanx Jun 05 '26

std::string(getenv(VAR) ?: "") ?

1

u/Total-Box-5169 Jun 06 '26

Unfortunately is not in the standard.

2

u/naikrovek Jun 06 '26

Friendly reminder that it is almost always configuration (such as environment variables) which causes “it works here, but not there”.

Your startup routine should make sure that all needed environment variables and configuration files are present and that they have sensible values before actually attempting to do any work.

1

u/max0x7ba https://github.com/max0x7ba Jun 06 '26 edited Jun 06 '26

Friendly reminder that it is almost always configuration (such as environment variables) which causes “it works here, but not there”.

This is a problem of configuration not being easily reproducible.

The environment variables do not create this problem, only aggravate the problem and make it apparent.

Your startup routine should make sure that all needed environment variables and configuration files are present and that they have sensible values before actually attempting to do any work.

Requiring setting any environment variables at all to run something is tedious, error-prone and brittle -- poor engineering. Environment variables should only be used for overriding default settings.


The best engineering practice is iterative configuration resolution, loading (partial) configuration from multiple sources in sequence, with subsequently loaded configuration values replacing any existing configuration values.

The canonical configuration load order is designed for:

  • specific configuration to override general / less specific,
  • explicit configuration to override implicit.

The order is:

  1. (implicit, general) The initial configuration values specified in the source code.
  2. (implicit, specific) Environment variables.
  3. (explicit, general) Config files.
  4. (explicit, specific) Command line options.

After all sources of configuration have been read, the software must log the complete resolved configuration in such a way, that allows its easy examination (e.g. as name=value lines sorted by name).

And a one-liner command to reproduce the run with the complete resolved configuration.

The command line must either pass the complete resolved configuration through command line options (when complete configuration is small enough to be specified in the command line options alone). Or, the complete resolved configuration must be saved into a config file (next to the log file), with the one-liner command loading that complete config file.

The complete resolved config file also solves the problem of easy examination of complete configuration, provided the configuration file format is human-friendly (which it should be).

That one-liner command with the complete configuration (inline and/or in the config file) is explicit configuration that overrides any environment variables. And it solves the configuration reproducibility problem -- the one-liner command reproduces the run robustly on any other machine/environment, and ignores any configuration in environment variables.

3

u/johannes1971 Jun 05 '26

It would cost us nothing to have std::string check for nullptr in the constructor, and just treat it as an empty string. This would avoid this kind of mistake, not just with this function, but with countless functions that are commonly used in the C ecosystem.

2

u/ProfesorKindness Jun 05 '26

There are other people that could spend day on stupid errors like that?

Thank god I am not alone.

2

u/chibuku_chauya Jun 06 '26 edited Jun 06 '26

Maybe std::string should be revised to deal with nullptr in a well-defined way. This is an unfortunate footgun that's bitten me multiple times in the past.

0

u/max0x7ba https://github.com/max0x7ba Jun 06 '26

Maybe std::string should be revised to deal with nullptr in a well-defined way.

That requires introducing an if statement into std::string constructor. The if statement may be cheap but that's not 0-cost -- the test and branch/cmov instructions introduce unnecessary costs into existing code. And that defeats the core C++ principle of paying only for what you use.

This is an unfortunate footgun that's bitten me multiple times in the past.

What made you expect that char const* pointers you initialized your std::string objects with couldn't possibly be null?

Did you actually need to copy-convert char const* pointers into std::string objects?

0

u/johannes1971 Jun 09 '26

If you want something that is a perfect for what you need, write it yourself. The default, standard solution is intended for a wider audience than just you, and should not have this kind of landmine in it.

The 'cost' you talk about is so small that it doesn't matter. If you cared about it at all, you wouldn't be calling a constructor that calls strlen() in the first place.

2

u/germandiago Jun 05 '26

I have this in my code:

std::optional<std::string_view> getEnv(std::string_view envVar) {
   auto var = std::getenv(envVar);
   if (var != nullptr)
       return std::string_view(var);
   return std::nullopt;
}

works like a charm for monadic stuff when you want to fallback to other values or fail, etc.

The var is guaranteed to end in a \0 also if present.    

5

u/Alarmed-Paint-791 Jun 05 '26

This should not pass code review. Three problems immediately jump out:

0) It does not compile. "std::getenv" takes a "const char*", not a "std::string_view".

  1. The argument, "envVar", must be null-terminated, but "std::string_view" provides no such guarantee. Simply passing "envVar.data()" would therefore not fix the underlying problem.
  2. The returned "std::string_view" refers to storage managed by the environment. Its lifetime and stability are outside your control. Any subsequent calls to setenv, unsetenv, putenv (or any other environment-modifying operation) may invalidate or overwrite it.

2

u/germandiago Jun 05 '26 edited Jun 05 '26

Actually I wrote it from the top of my head, the one in my codebase is indeed const char * for exactly the same reason you mention.

Never thought of 2. bc in my environment is of no concern, but thanks for that! Maybe I should duplicate the string.

1

u/soylentgraham Jun 05 '26

isn't there a safe version that writes to a buffer you provide instead of passing around pointers?

1

u/Annual-Examination96 Jun 05 '26

You probably need a good stacktrace library in your project. I would recommend CPPTRACE. It can help you to pinpoint the cause of exceptions even on release builds.

1

u/Neat-Exchange6724 Jun 07 '26

A better lesson to learn is: Never under any circumstance read anything from env.

1

u/HommeMusical Jun 05 '26

This should have been something that could be detected at compile time.

Oh, don't get me wrong. I know it's impossible. char* is essentially a union type of "a valid pointer to a string of characters" and nullptr, and some sort of warning flag, "warn on possible nullptr", would generate so many warnings that it would be unusable.

So there is no way to look at const char* foo() and know whether or not it can actually return nullptr and as far as I know, there's no way to annotate existing functions to let the compile know.

I know all this. But here we are, forty years later, and people are still running into the same issues I was running into in the 1980s, and the tooling does nothing.

1

u/max0x7ba https://github.com/max0x7ba Jun 06 '26 edited Jun 08 '26

The 0-cost solution is trivial:

char const* getenv2(char const* name, char const* default_value) noexcept {
    char const* value = std::getenv(name);
    return value ? value : default_value;
}

default_value replaces nullptr return values without losing the ability to distinguishing unset environment variables by comparing the return value with default_value argument instead of nullptr.

Copying the result into an std::string involves memory allocation and data copying -- unnecessary waste.

Wrapping the result into std::string_view is 0-copy, but still calls std::strlen. If the result is next parsed into an integer or floating point value, then calling std::strlen is unnecessary waste.


Functions returning pointers are expected to return null pointers too, unless explicitly documented otherwise. Are you going to post a separate PSA about every function that returns null char const* pointer?

Return values are specified in function documentation, which you should at the very least skim through when calling a function for the first time, to be able to handle all its possible return values robustly without failures. That saves you from having to waste time in the future on investigating and debugging errors caused by inadequate handling of return values, reading the documentation, reproducing the error and verifying its fix. Failing to handle documented return implies lack of due diligence, thought and care which undermine trust and reputation.

0

u/[deleted] Jun 05 '26

[deleted] — view deleted comment

1

u/chibuku_chauya Jun 05 '26

Whoa, did you use the preprocessor to Rustify C++ ?