Search

6.7a — Null pointers

Null values and null pointers

Just like normal variables, pointers are not initialized when they are instantiated. Unless a value is assigned, a pointer will point to some garbage address by default.

Besides memory addresses, there is one additional value that a pointer can hold: a null value. A null value is a special value that means the pointer is not pointing at anything. A pointer holding a null value is called a null pointer.

In C++, we can assign a pointer a null value by initializing or assigning it to the literal 0:

Because a null pointer evaluates to 0, it can be used inside a conditional to test whether the pointer is a null pointer or not:

Best practice: Initialize your pointers to a null value if you’re not giving them another value.

Dereferencing null pointers

In the previous lesson, we noted that dereferencing a garbage pointer would lead to undefined results. Dereferencing a null pointer also results in undefined behavior. In most cases, it will crash your application.

The NULL macro

C (but not C++) defines a special preprocessor macro called NULL that is #defined as the value 0. Even though this is not technically part of C++, its usage is common enough that it should work in every C++ compiler:

However, because NULL is a preprocessor macro and because it’s technically not a part of C++, best practice in C++ is to avoid using it.

nullptr in C++11

Note that the value of 0 isn’t a pointer type, so assigning 0 to a pointer to denote that the pointer is a null pointer is a little inconsistent. In rare cases, when used as a literal argument, it can even cause problems because the compiler can’t tell whether we mean a null pointer or the integer 0:

To address these issues, C++11 introduces a new keyword called nullptr. nullptr is both a keyword and an rvalue constant, much like the boolean keywords true and false are.

Starting with C++11, this should be favored instead of 0 when we want a null pointer:

C++ will implicitly convert nullptr to any pointer type. So in the above example, nullptr is implicitly converted to an integer pointer, and then the value of nullptr (0) assigned to ptr.

This can also be used to call a function with a nullptr literal:

Best practice: With C++11, use nullptr to initialize your pointers to a null value.

std::nullptr_t in C++11

C++11 also introduces a new type called std::nullptr_t (in header <cstddef>). std::nullptr_t can only hold one value: nullptr! While this may seem kind of silly, it’s useful in one situation. If we want to write a function that accepts a nullptr argument, what type do we make the parameter? The answer is std::nullptr_t.

You probably won’t ever need to use this, but it’s good to know, just in case.

6.8 -- Pointers and arrays
Index
6.7 -- Introduction to pointers

12 comments to 6.7a — Null pointers

  • csvan

    I believe there is an error in the last example in the section “the null pointer” here: did you not mean to dereference the pointer inside the if-condition, in order to check wether or not it points to anything? Right now it is written without a dereference operator.

    Keep coding. Use it for good 🙂

    • baldo

      The if (pnPtr) test to see if the pointer is null. If it is a null pointer then the address it is pointing is 0 (false). If the pointer is allocated (not null) then pnPtr points to a address != 0 (which means true).

  • Typo in the second code example:

    in 4th line, "an double" should be "a double".

  • Jim

    Alex,
    At the beginning of this lesson you introduced a null pointer, int *ptr(0); which was changed to int *ptr = nullptr
    by C++11. I still like the former!

    Was this done since int*prt(5) and int *prt = 5 are both improper syntax. Since you can not assign a literal to a pointer variable?

    • Alex

      It was done mainly to help disambiguate whether a literal 0 was intended as an integer or null pointer. If you like the old-style, it will certainly continue to be supported.

  • alex be like

    number.number

    introduction blablablablablablablabla

    some codes

    prints
    bla

    blablablabla….
    .
    .
    .
    .
    .
    .
    some thousand lines, 1 hour and a headache later
    rule: you won’t need those. *insert troll face here*

    I love your tutorials
    you are the best.. 🙂

    • Alex

      Haha. If you think these programs are long, wait until you get to the comprehensive quiz for this chapter! 😉

      • J3ANP3T3R

        Question : the use of assigning nullptr to a pointer is so that we can check later if it is not pointing to anything ? or are there any other use for it ?

        • Alex

          Yes, that’s right. We use nullptr as a way to say, “this pointer isn’t pointing to anything right now”. That way, we can determine whether the pointer is pointing to something or not via a simple if statement.

          The other (related) use for nullptr is to pass a null value into a pointer function parameter.

          • Hussain

            Amazing lessons Alex, Thanks a million 😉

            I was told that one bad use of pointers is to make pointers that point to nothing (AKA, dangling pointers). From above, I have the feeling that I was misinformed in the past!

            Would you kindly give example on uses we want to pass null value into a pointer function parameter?

            Also, is it true that null as an argument isn’t as ()?

            Thanks in advance =)

            • Alex

              Let’s be careful what we mean by “nothing”. Null pointers and dangling pointers are not the same thing.

              A null pointer points to “nothing” (address 0). That is okay, because “nothing” is an acceptable known value that we can test for and work around.
              A dangling pointer points to a valid memory address, but not one that has been allocated for your application’s use. These are he pointers that will get you in trouble, because there’s no way to distinguish a dangling pointer from a valid one.

              I added an academic example of passing a nullptr to a function in the lesson. While this isn’t particularly useful, it does show the mechanics. As for useful examples, we’ll see some of those when we get into classes and object-oriented programming (in particular, we use a special type of function called a constructor to initialize our classes -- if our class contains a pointer and we want to initialize it to a null value, we’d pass in a null value).

              > Also, is it true that null as an argument isn’t as ()?

              null (0 or nullptr) is an explicit literal value, whereas () is an empty argument. They are definitely not the same thing -- one is an argument, one is the lack of an argument.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter