简体   繁体   中英

How do I check if a pointer points to NULL?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM