I’ve found some code like (many problems in the following code):
//setup consistent in each of the bad code examples
string someString;
char* nullValue = getenv("NONEXISTENT"); // some non-existent environment variable
// bad code example 1:
char x[1024];
sprintf(x," some text%s ", nullValue); //crashes on solaris, what about linux?
// bad code example 2:
someString += nullValue; // What happens here?
//bad code example 3:
someString.append(nullValue); // What happens here?
//bad code example 4:
string nextString=string(nullValue); //What happens here?
cout<<nextString;
We’re using solaris, linux, gcc, sunstudio, and will quite possibly use clang++ in the future. Is the behaviour of this code consistent across platform and compiler? I couldn’t find specs that describe expected behaviour in all the cases of the above code.
At present, we have problems running our code using gcc (and on linux), is the above code a likely cause?
If the code above acts the same in all of these environments, that’s valuable information (even if the behavior is a crash) for me because I will know that this isn’t the reason for our linux problems.
In general these uses of NULL, where a valid C string is expected, cause undefined behavior, which means that anything can happen.
Some platforms try to have defined behavior for this. IIRC there are platforms that deal gracefully with passing a NULL pointer to printf family functions for a %s format substitution (printing something like “(null)”). Other than that, some platforms try to ensure a reproducible crash (e.g. a fatal signal) for such cases. But you can’t rely on this in general.
If you have problems in that area of the code: yes, this is a likely cause or may obscure other causes, so: fix it, it’s broken!