How do I check if a pointer points to NULL?
c, c++, null
Solution
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.
Problem
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.