简体   繁体   中英

pointers c++ - access violation reading location

output: Access violation reading location 0x0093F3DC.

i cant seem to figure out the problem. the head and next pointers are initialized with null in respective constructors.

class List{ 
public: 
    node *head;
    List(void)  // Constructor      
    { 
        head = NULL; 
    }   
    void insertNode(int f)  
    {
        node *newNode;
        newNode=new node();
        newNode->value = f;
        newNode->next=head;
        head=newNode;
    }   
    void displayList()
    {
        node *ptr=head;
        while (ptr!=NULL)
        {
            cout<<ptr->value<<endl;
            ptr=ptr->next;
        }
    }

    bool search( int val)
    {
        node *ptr= head;
        while (ptr!=NULL)
        {
            if(ptr->value == val)
            {
                return true;
            }
            ptr=ptr->next;
        }
        return false;   
    }

};

Most likely, it is better to declare only a pointer, instead of allocating a Node instance then wiping out the newly allocated memory (eg causing a dangling memory leak). For example:

bool search( int val)
{
    //
    // Declare the pointer to traverse the data container, assign to the head
    // This works only if head is valid.  It is assumed that head is pointing 
    // to valid memory by the constructor and/or other class member functions.
    //
    node *ptr = this->head;
    while (ptr!=NULL)
    {
        if(ptr->value == val)
        {
            return true;
        }
        ptr=ptr->next;
    }
    return false;   
}

In the class implementation details above, the internal head pointer is always assigned to the newNode memory inside InsertNode. Consequently head moves every time InsertNode is called. Is this the desired functionality?

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