r/cpp • u/SmokeMuch7356 • 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.
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?
7
u/saxbophone mutable volatile void Jun 05 '26
Maybe you should actually read the error messages next time
10
u/tim_pipperton Jun 04 '26
Shouldn’t they be a (potentially const) string_view?
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?
123
u/No-Dentist-1645 Jun 05 '26 edited Jun 05 '26
I always use this short wrapper function:
It lets me do cool functional composition such as:
9
u/Tidemor Jun 04 '26
That title is a bit misleading tho, don't you think?
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...
58
u/Healthy-Act3539 Jun 04 '26 edited Jun 04 '26
This is how I usually do it:
Checks both if the variable exists and is not empty. Works well enough.
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:
5
u/_Noreturn Jun 05 '26
This is why you make a wrapper I make a
GetEnv<std::string>("Name")template, same forGetEnv<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) ?: "")?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.
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::stringshould be revised to deal withnullptrin a well-defined way. This is an unfortunate footgun that's bitten me multiple times in the past.2
u/germandiago Jun 05 '26
I have this in my code:
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.
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" andnullptr, and some sort of warning flag, "warn on possiblenullptr", 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 returnnullptrand 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:
default_valuereplacesnullptrreturn values without losing the ability to distinguishing unset environment variables by comparing the return value withdefault_valueargument instead ofnullptr.Copying the result into an
std::stringinvolves memory allocation and data copying -- unnecessary waste.Wrapping the result into
std::string_viewis 0-copy, but still callsstd::strlen. If the result is next parsed into an integer or floating point value, then callingstd::strlenis 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