访问空指针会导致seg错误

时间:2013-12-05 21:22:06

标签: c++ segmentation-fault

我有一个基于模板的类:

template <typename T>
class Foo
{
    public:
        Foo();
        bool iterateFoos();
    private:
        Foo<T> *babyFoos[5];
};

在构造函数中,我设置了所有babyFoos = NULL:

template <typename T>
Foo<T>::Foo()
{
    for(int i =0; i<5; i++) babyFoos[i] = NULL;
}

此if条件会引发seg错误:

template <typename T>
bool Foo<T>::iterateFoos()
{
    for(int i=0; i<5; i++)
    {
        if(babyFoos[i] != NULL) { do stuff }
    }
}

我不明白为什么?

1 个答案:

答案 0 :(得分:1)

如果if条件本身导致了段错误,那意味着thisiterateFoos()的值无效 - 也许你在调用它时取消引用null /悬空指针

相关问题