Pegah
Pegah

Reputation: 682

Segmentation fault when reading a vector

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

Upvotes: 6

Views: 1679

Answers (5)

Blastfurnace
Blastfurnace

Reputation: 18652

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).

Upvotes: 3

moinudin
moinudin

Reputation: 138397

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/

Upvotes: 1

osgx
osgx

Reputation: 94345

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

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190966

I wonder if you might be messing with the stack.

Wrap this

if (v[i]>0) ++pos; else ++neg;

in curly braces.

{ if (v[i]>0) ++pos; else ++neg; }

Upvotes: 0

unquiet mind
unquiet mind

Reputation: 1112

This:

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

should be:

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

and similar elsewhere.

Upvotes: 0

Related Questions