vector issue

Using devc++ 4.9.9.2 to compile the following constructor. There are no compile errors, however the code produces a seg fault at the resize command which is inside the constructor. Comment the resize line out and it Seg faults after 16 times thru the for loop.

Any ideas why this is happening?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Element{
      private:
      public:
          Element();
          ~Element(){};
          int counter;
          float val;  
          float slope;
          int counterToPrevMin;
          int counterToPrevMax;
          float var1;
      protected:
      };


Indicator::Indicator(int num){
        vector<Element> tmp;
        tmp.resize(2000);
        int i;
        for (i = 0; i<num ; i++){
               tmp.push_back(Element());
        }
        lmnt = tmp;
        it = lmnt.begin();
        indName = "\0"; 
        firstRecord = NULL;
        numRecords = 0;
       }
Last edited on
std::vector<Element>(2000, tmp);

You can just use something like that can't you?
Hrm, try putting .reserve(2000) in front of the resize...although if it is generating a segfault using just .pushback()...I don't really know what the problem is (unless you are running out of memory space or something)
Thanks for your replies, still no luck. I have been working with the debugger and discover that the segfault happens on multiples of 8.

Depending on the object in the <vector>, ie integer or double, it will segfault in various places in the loop(64, 128, etc). It appears that when the pushback function hits the capacity boundary, it does not always reallocate memory for the next object.

I have tried this on more than one computer and it reproduces the same problem. I am starting to think my vector.h is corrupted.

I am starting to think my vector.h is corrupted.
No.

Post more code. I don't see anything that could producing the problem in the code you posted.
Last edited on
back to the basics. Loaded a small amount of code into a new project, to prove the complier etc was working.
1
2
3
4
5
6
7
8
9
10
11
12
13
int main(){
    
    vector<Element>* tmp = new vector<Element>;
    int i;
    int ssize = 21000;
    tmp->resize(ssize);
    for( i=0 ; i<ssize; i++){
            tmp->push_back(Element());
    }
    printf("%d records created %d\n",i,sizeof(Element));
    cin>>i;
    
}


It works flawlessly now, even using dynamic memory. I obviously have a leak in my project somewhere. Will post it when I uncover it.

Thanks for the replies.
Your code is doing something other than what you think. I recommend reading the reference on std::vector::resize().
"mea maxima culpa"

helios you are correct. here was the problem.

Record* rData = new Record[_numRecords+1];

simple as that. added the +1 to the array size and it all works.

Curses to Bjarne for starting arrays at 0. Until next time...
Topic archived. No new replies allowed.