The title may be a little bit of a misnomer... just because I'm not sure if my char pointer is pointing to NULL, or if it's just pointing to a char array of size 0.
So I have
char* data = getenv("QUERY_STRING");
And I want to check if data is null (or is length < 1). I've tried:
if(strlen(data)<1)
but I get an error:
==24945== Invalid read of size 1
==24945== at 0x8048BF9: main (in /cpp.cgi)
==24945== Address 0x1 is not stack'd, malloc'd or (recently) free'd
I've also tried
if(data == NULL)
but with the same result.
What's going on here? I've already tried cout with the data, and that works fine. I just can't seem to check if it's null or empty.
I realize these are two different things (null and empty). I want to know which one data would be here, and how to check if it's null/empty.
Hence when a pointer to a null pointer is created, it points to an actual memory space, which in turn points to null. Hence Pointer to a null pointer is not only valid but important concept.
It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer.
In C or C++, there is no special method for comparing NULL values. We can use if statements to check whether a variable is null or not.
With getenv, you have to handle both cases! (Yay!) If the environment variable is not set, then the function returns NULL. If it is set, then you get a pointer to the value it's set to, which may be empty. So:
const char* data = getenv("QUERY_STRING");
if (data != NULL && data[0] != '\0') {
// Variable is set to value with length > 0
// ...
}
Obviously, you need to check if it's NULL before attempting to determine its length or read any of the characters it points to -- this is why the two conditions in the above if
are ordered the way they are.
Generally you'd check with something like this. The first part checks the pointer for null, the second checks for an empty string by checking the first character for the null terminator at the end of every string.
if (data == NULL || data[0] == 0)
Your problem looks like some specific interaction between getenv
and strlen
that isn't standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With