简体   繁体   English

指针C ++-访问冲突读取位置

[英]pointers c++ - access violation reading location

output: Access violation reading location 0x0093F3DC. 输出:访问冲突读取位置0x0093F3DC。

i cant seem to figure out the problem. 我似乎无法找出问题所在。 the head and next pointers are initialized with null in respective constructors. head和next指针在各自的构造函数中初始化为null。

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). 最有可能的是,最好只声明一个指针,而不是先分配一个Node实例,然后再擦除新分配的内存(例如,导致内存泄漏)。 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. 在上面的类实现详细信息中,内部头指针始终分配给InsertNode内部的newNode内存。 Consequently head moves every time InsertNode is called. 因此,每次调用InsertNode时磁头都会移动。 Is this the desired functionality? 这是所需的功能吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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