分段故障和吸气剂问题

时间:2012-04-13 10:15:09

标签: c++ segmentation-fault getter

我有一项跟踪人员的任务,现在我需要进行crud操作。 当我尝试访问动态数组时,人的id的getter工作,但是一个人的手机返回“分段错误”,而人的名字则不显示任何内容。

//the main.cpp test that gives the following error
Controller ctrl(repp,repa,valp,vala);
ctrl.addPerson(1,"Name","0744000000","Adress");     
ctrl.show();

//controller show method, repp - instance of repository in controler
void Controller::show()
{
    repp->show();
}

//repository show method, which doesn't work
void PersonInMemoryRepository::show()
{
    for(int i=0; i < pers.getSize(); i++)
        cout<<pers.get(i)->getName()<<endl;
}

//getById method in repository
const Person* PersonInMemoryRepository::getById(int id)
{
for (int i = 0; i < pers.getSize(); i++) 
    {
    if (pers.get(i)->getId() == id) {
        return pers.get(i);
                                    }
}
return NULL;
}

 //the Person class
 class Person 
 {
 public:
Person(int i, string n, string p, string a);
const string& getName() const {
    return name;
}
const string& getPhone() const {
    return phone;
}
const string& getAdress() const {
    return adress;
    }
int getId() const {
    return id;
}
    ~Person();
 private:
    int id;
string name;
string phone;
string adress;
};
//pers.get(i)
template<typename Element>
Element DynamicArray<Element>::get(int poz) {
return elems[poz];
}

提前致谢。

更新:当它在行cout&lt; getName(); 。 pers.get(i)工作正常,它是Person *类型向量,当我在调试器中取消引用它时,它具有正确的值,但在 - &gt; getName()它表示“无效的重复次数0”。

2 个答案:

答案 0 :(得分:1)

虽然你没有显示足够的代码来完全理解这个问题,但是假设pers是标准库中的某种形式的容器,大多数大小的函数会给出从一个开始计数的元素数量大小的结果。容器从零开始。这意味着要正确访问所需的所有元素,需要从容器的大小中减去一个元素。

如果这个假设为真,那么for循环的正确代码是:

for (int i = 0; i < pers.getSize()-1; i++)

答案 1 :(得分:0)

您显示的代码不足以弄清楚导致seg的原因。故障。我的猜测是你过度索引到elems容器(也许pers.getSize()可能返回错误的值?)