Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a pointer points to NULL?

Tags:

c++

c

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.

like image 380
varatis Avatar asked Apr 26 '12 20:04

varatis


People also ask

What happens when a pointer points to null?

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.

Can pointers be set to null?

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.

How do you check if something is null in C++?

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.


2 Answers

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.

like image 116
Cameron Avatar answered Oct 23 '22 21:10

Cameron


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.

like image 21
Mark Ransom Avatar answered Oct 23 '22 23:10

Mark Ransom