开发者

passing a vector pointer to a function causes segfault

I am passing a vector pointer to another fu开发者_运维技巧nction which pushes data using that pointer:

void foo(vector<pair<int,int>> * vp){
 vp->push_back(pair<int,int>(1,1)); //causes segfault
}

void bar(vector<pair<int,int>> *vp = NULL){
  foo(vp);
}

The push_back causes segfault.


If you call bar without a parameter, then vp will be NULL. Then foo is passed a NULL pointer and thus, this instruction vp->push_back will generate the segmentation fault.


If it hurts, don't do it. You should almost never pass things like vectors using pointers - use references instead:

void foo(vector<pair<int,int>> & vp){
 vp.push_back(pair<int,int>(1,1));
}


I'm guessing your vector is NULL ... you'll want to add a check in foo.

void foo(vector<pair<int,int>> * vp)
{
    if (vp != NULL)
        vp->push_back(pair<int,int>(1,1));
}

Also prefer use of nullptr if you have C++0x support in your compiler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜