简体   繁体   中英

Segmentation fault i cant figure out

I have the following constructor:

    Timing::Timing():
    _numMes(INIT_NUMMES),_msgs(new allMSgs*[NUMBER_OF_MSGS])
    {

        cout<<"build timing OK\n";
    }

allMSgs is a struct :

   typedef struct AllMSgs
   {
            double msg;
        Agent* dedicatedTo;
   }allMSgs;

and the declaration of it is done like this:

        allMSgs** _msgs;

but when i try to reach for a field in the array like this:

     _msgs[loc]->dedicatedTo=agent->getPointsTo();

i get a segmentation fault.

NUMBER_OF_MSGS is 1000

loc is 0,1,2.... (less then 1000);

help please

You've made an array of pointers, but not set them to point anywhere valid yet. You either need to change it to be simply:

allMSgs* _msgs;

and:

new allMSgs[NUMBER_OF_MSGS]

Or call new for each pointer in the allMSgs array.

Better yet though you could just use a std::vector or other container, with std::vector<allMSgs> _msgs; , which you can use like it was an array in most cases. You can initalise it with a size too.

You have only allocated the array itself. You need to allocate each and every item of the array too. In the constructor, add a for loop that allocates all of the items.

for (int i = 0; i < NUMBER_OF_MSGS; i++)
  _msgs[i] = new allMSgs();

You can also just define the array as an array of allMSgs and not pointers to allMSgs .

allMSgs* _msgs;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM