Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault when reading a vector

Tags:

c++

stl

in a c++ program, when I want to read a vector with the size of 2697806, I always get the Segmentation fault error. I have had tried all possible ways of reading it:

void AUROC(vector<float> v) {
   ...
   for(std::vector<int>::size_type i = 0; i != v.size(); i++)
      if (v[i]>0) ++pos; else ++neg;

   for(std::vector<long>::size_type i = 0; i != v.size(); i++)
     if (v[i]>0) ++pos; else ++neg;

   for (vector<float>::iterator i=v.begin(); i!=v.end(); ++i)
     if (*i>0) ++pos; else ++neg;

   for (long i=0;i<=v.size();i++)
     if (v[i]>0) ++pos; else ++neg;

   for(int i=0;i<=v.size();i++)
     if (v[i]>0) ++pos; else ++neg;
}

...
int main(void) { 
    vector<float> scores;
    // put data in scores;
    AUROC(scores);
}

this problem never happens with the vectors of much smaller sizes.

Thanks for your help. Best, Pegah

like image 258
Pegah Avatar asked Dec 17 '10 22:12

Pegah


3 Answers

I know you've accepted an answer already but your posted code has a problem with the following loop:

for(int i=0;i<=v.size();i++)

The vector indexes are zero-based. If the vector size is 5 then the valid indexes are 0..4. Your code would try to access elements 0..5 which is an off-by-one error. I believe your "fix" of the stack size is merely masking other real problems.

In addition, you should be passing the vector by reference, not by value. You are currently copying the vector when you call AUROC(vector<float> v). This is slow and an extravagant waste of memory. Change the function to AUROC(vector<float> &v).

like image 147
Blastfurnace Avatar answered Sep 17 '22 14:09

Blastfurnace


When you call your function as:

vector<float> scores;
// put data in scores;
AUROC(scores);

The scores vector will be copied into the stack. You should not to pass so large data collections (12 MBytes) via stack, change your code to reference or to pointer passing.

Also, you can check and change stack limits on you Host. On unix:

ulimit -s 

will print the current setting of stacklimit. You can change it by

ulimit -s size_in_kb

and check it after changing

like image 24
osgx Avatar answered Sep 20 '22 14:09

osgx


Since it works for smaller sizes, my best guess is that you're running out of stack space. How to check the stack space and changing it depends on your OS: On Linux run ulimit -s to check and ulimit -s SIZE to set.

Further reading: http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/

like image 32
moinudin Avatar answered Sep 21 '22 14:09

moinudin