Aug 31, 2019 at 11:52am UTC
This code gave me "Process returned -1073741819 (0xC0000005) execution time : 2.583 s", why is that? There is nothing wrong with this code.
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 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
#include <vector>
using namespace std;
class Victim{
private :
int ss;
public :
Victim(int ss):ss(ss){}
int getSs(){return ss;}
};
class Troll{
public :
vector<Victim> collection;
Troll(vector<Victim> collection);
};
Troll::Troll(vector<Victim> collection){
for (int i=0; i< collection.size();i++){
this ->collection[i] = collection[i];
}
}
int main()
{
vector<Victim> a;
a.push_back(Victim(5));
a.push_back(Victim(6));
Troll z( a);
cout << z.collection.at(0).getSs() << endl;
return 0;
}
Last edited on Aug 31, 2019 at 11:53am UTC
Aug 31, 2019 at 12:23pm UTC
If there's nothing wrong with it, why is it crashing?
Okay but for real: in your Troll constructor, you are assigning to this->collection[i] but that element doesn't exist. The size of your vector is 0.
Use push_back instead, or call resize() before the loop.
Last edited on Aug 31, 2019 at 12:24pm UTC
Aug 31, 2019 at 1:18pm UTC
Better yet,
initialize the collection with collection:
1 2 3 4
Troll::Troll(const vector<Victim>& collection)
: collection(collection)
{
}
PS. Line 39 calls at(), but line 25 uses []. The at() will report out-of-range mistake, but the [] does not; all you get is silent corruption (or not so silent, if it yields immediate crash). Put other way, you had some safety measure in one place but not everywhere. That could be intentional, but more likely just sloppy.
Last edited on Aug 31, 2019 at 1:19pm UTC