-3

Trying to create a function which will fill a vector of objects with initialized objects. Please help. ERROR: Segmentation fault (core dumped)

EDIT:

Ok so, problem seems to be occurring in the line when trying to access OBJ[0].age.

Also forgot the Point2d function comes from OpenCV libraries which I forgor to add, but they dont seem to contribute to the error in any way.

#include <iostream>
#include <vector>

struct objtracker
{

int age;
vector<int> frID;
vector<Point2d> cent;
    objtracker()
    {
        age = 1;        
    }
    ~objtracker()
    {
    // Destroy ObjectTracker
    }
};

vector<objtracker> OBJ;

void create_new_tracker(vector<objtracker> OBJ,Point2d cent,int frameID,objtracker O){


    O.cent.push_back(cent);
    O.frID.push_back(frameID);


}
int main(){

    Mat Y;
    Y = imread("hor.jpeg",CV_LOAD_IMAGE_COLOR);
    Point2d J;

    J.x = 100;
    J.y = 100;
    int frameID = 100;
        objtracker O;
        create_new_tracker(OBJ,J,frameID,O);
        create_new_tracker(OBJ,J,frameID,O);
        create_new_tracker(OBJ,J,frameID,O);
        create_new_tracker(OBJ,J,frameID,O);
        create_new_tracker(OBJ,J,frameID,O);

    cout<<OBJ[0].age<<"\n";

return 1;   }
M.M
  • 138,810
  • 21
  • 208
  • 365
  • Would you be so kind as to replace your rant with a useful description of what your code is supposed to do and where it crashes ? – Quentin May 26 '16 at 08:18
  • Embrace the change :-). Btw the old school way still works, but the libraries should make it easier for you. – Stefan May 26 '16 at 08:19
  • 1
    Parameter `objtracker O` - that would be a *value* parameter. The caller's vector remains quite-empty. And `OBJ` is never populated with *anything* in this code, so I'm not surprised that subscript operator faults. Suggest [a good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and some re-ramp-up time would be in order? – WhozCraig May 26 '16 at 08:19
  • Thank you for your attention, now have fixed it with more info. Ok so maybe call by reference? – MyBushisaNeonJungle May 26 '16 at 08:24
  • @WhozCraig haha yeep dont know how I made that mistake. This is what is called a brain fart I guess. – MyBushisaNeonJungle May 26 '16 at 08:31
  • 2
    I have rolled back to the previous edit. Solutions should be posted in the Answer box, not in the Question. – M.M May 26 '16 at 09:05

1 Answers1

1
   void create_new_tracker(vector<objtracker> OBJ,Point2d cent,int frameID,objtracker O){
O.cent.push_back(cent);
O.frID.push_back(frameID);
 }

You never add any objtracker's to OBJ inside this function. And even if you did, it won't be reflected as it is passed by value You might want something like

      void create_new_tracker(vector<objtracker> &OBJ,Point2d cent,int frameID,objtracker O)
      {
         O.cent.push_back(cent);
         O.frID.push_back(frameID);
         OBJ.push_back(O);
       }
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34