简体   繁体   中英

Why doesn't this loop detect null pointer?

So this is my code:

while(node) {
    cout<<node->getDiameter();
    node=node->stepAbove();
}

these are the methods:

Node* Node::stepAbove() {
    return this->above;
}
int Node::getDiameter() {
    return this->r;
}

but the while loop causes the Access Violation, because the loop doesn't detect a null pointer. When debugging, it points to an address "0xcccccccc" which has nothing defined... Any suggestion where the problem is?

EDIT: Forgot to post my constructor is:

Node(int x=0) {
    this->above=nullptr;
    this->r=x;
}

There is a difference between the uninitialized pointer and the null pointer in C++

struct node
{

};

int main()
{
    node *n1 = 0;
    node *n2;

    if(!n1)
        std::cout << "n1 points to the NULL";

    if(!n2)
        std::cout << "n2 points to the NULL";
}

Try to run this code and you will see that n2 points to the NULL won't be printed. You wonder why? That is because n1 has been explicitly pointed to the null , but I wasn't done the same with n2 . The С++ standard does not specifies what address the uninitialized pointer should hold. And there, 0xcccccccc is seems to be the address that your compiler chosen to be default for the debug mode.

In your constructors, set fields to NULL that are not initialised by constructor parameters, for example:

Node::Node(float radius) 
{
    above = NULL;
    r = radius;
}

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