首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pointers c++ -访问冲突读取位置

pointers c++ -访问冲突读取位置
EN

Stack Overflow用户
提问于 2014-03-24 01:20:03
回答 1查看 1.1K关注 0票数 0

输出:访问冲突读取位置0x0093F3DC。

我似乎找不出问题所在。头指针和下一个指针在各自的构造函数中初始化为null。

代码语言:javascript
复制
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;   
    }

};

EN

回答 1

Stack Overflow用户

发布于 2014-03-24 01:27:21

最有可能的是,最好只声明一个指针,而不是分配一个Node实例,然后清除新分配的内存(例如,导致悬空内存泄漏)。例如:

代码语言:javascript
复制
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;   
}

在上面的类实现细节中,内部头指针总是分配给InsertNode内部的newNode内存。因此,每次调用InsertNode时,head都会移动。这是所需的功能吗?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22594251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档