Vector of vector : Segmentation Fault - c++

I have a segmentation fault error at runtime, here is my code with an indication of the line where the error occurs :
EDIT : the variable Scenario is an attribute of the class Probleme, the code I posted is the code of its constructor
EDIT : The error happens at runtime
class scenario
{
public:
int id;
std::vector<std::vector<int> > demandes;
scenario() {}
void setid(int i) { id=i; }
void setdemande( std::vector<int> v) { demandes.push_back(v); }
int getid() const { return id; }
};
Scenario.resize(nb_scenario);
for (int i = 0; i < nb_scenario; ++i)
{
Scenario[i].setid(i);
}
int s;
for(int i=0; i<nb_periode ; i++) {
fichier >> s ;
for(int j=0;j<nb_produit;j++){
fichier >> s ;
for(int k=0;k<nb_scenario;k++){
fichier >> s;
Scenario[k].demandes[j][i]= s; //Error here
}
}
}

You never add anything to the demandes vector. Calling operator[] on an empty vector (the index is always out of bounds) is undefined behavior.
To fix this add elements to demandes using push_back or resize. To resize the inner vectors at the same time you can do demandes.resize(N, std::vector<int>(M)). Also consider using at instead of operator[], since it will throw an exception on an out of bounds access instead of causing undefined behavior.

Related

method giving app crashes due to segmentation fault in c++

this simple loop method is unable to run and an error arises "app crashed". when i checked this in an online compiler it gave 'segmentation fault(core dumped)'-
string studies(setMatter ch) {
string a = "LISTEN CAREFULLY!\n";
int i = 0;
while (i <= ch.a.quantity()) {
a += ch.a.getAns(i);
i++;
}
return a;
}
also see for reference of methods in the above code-
class Answer {
private:
vector<string> ch;
public:
void setAns(string ans) { ch.push_back(ans); }
string getAns(int num) { return (ch[num]); }
int quantity() { return ch.size(); }
};
am i accessing elements out of bond? but i dont know where as i every number starts from 0 in programming
Yes you are.
while(i<=ch.a.quantity()){
should be
while(i<ch.a.quantity()){
Valid vector indexes are zero up to the size of the vector minus one. That should be obvious, if the valid indexes started at zero and went to the size of the vector then there would be one more valid index than the size of the vector, which makes no sense.
Generally you use a for loop for this kind of task
for (int i = 0; i < ch.a.quantity(); i++) {
a += ch.a.getAns(i);
}
It's a little easier to read that way.

Unable to access vector value by index

#include<iostream>
#include<vector>
using namespace std;
class Stack
{
public:
int top;
vector<int> v;
Stack(int size)
{
top=0;
cout<<"Enter the values"<<endl;
for(int i=0; i<size; i++)
{
int val;
cin>>val;
v.push_back(val);
top++;
}
}
void push(int val)
{
v.push_back(val);
top++;
}
int pop()
{
int x=v[top];
top--;
return x;
}
void disp()
{
for(int j=top; j<=0; j--)
cout<<v[j]<<' ';
}
};
int main()
{
Stack s(3);
int k=s.pop();
cout<<k;
return 0;
}
I am trying to learn the basics of OOP.
Here, my Stack constructor and push function are working fine, but there is a problem with the pop and disp functions.
I'm assuming that I am using an incorrect syntax to access the elements of a vector(maybe?). Can anyone tell me where I am going wrong?
Also, the value of k always comes out to be 0.
You can use the vector functions
int k = s.back();
s.pop_back();
cout << k;
more informationhttp://www.cplusplus.com/reference/vector/vector/back/
You have a off-by-one index error.
The way you have implemented your class, when there are N items in the stack, the value of top is N.
Hence, top is not a valid index to access the elements of v. You can use:
int pop()
{
int x=v[top-1];
top--;
return x;
}
or
int pop()
{
top--;
int x=v[top];
return x;
}
As some of the other answers say, you can use the built-in vector functions to do these things (see pop_back and back.
However, if you want to define your own, I would use the vector.at(index) function. Addressing the values with the index as you have works, but it doesn't do any bounds checking at() does. Which would solve your problem above where your index isn't correct for the zero-based indexing of a vector.

New to C++, program not responding when dereferencing part of a vector?

I learned C++ yesterday an I'm trying to solve USACO training problems.
http://train.usaco.org/usacoprob2?a=iKSzALidh4Q&S=gift1
For this one, I have created a vector of People pointers. However, after some troubleshooting, I discovered that when I try to do something like
Person bob = *(people.at(i));
or
people.at(i) -> setbalance(giveself); // giveself is an int
The program is not responding and:
Process terminated with status -1073741819 (0 minute(s), 3 second(s).
I'm also new to this forum.
Here is my code:
include statments
using namespace std;
class Person
{
private:
int balance;
int origbalance;
string name;
public:
int getbalance() {return balance;}
string getname() {return name;}
void setbalance(int b){balance +=b;}
void setorigbalance(int o) {origbalance = o;}
int getorigbalance() {return origbalance;}
void giveTo(int num, Person* y) {y->setbalance(num);}
~Person();
Person(string n);
};
Person::Person(string n)
{
name = n;
}
Person::~Person()
{
}
int main()
{
ofstream fout ("gift1.out");
ifstream fin ("gift1.in");
int NP;
fin>>NP;
cout<<NP<<endl;
vector<Person*> people(NP);
cout<<"Created vector\n"<<endl;
for(int i = 0; i<NP; i++)
{
string nam;
fin>>nam;
Person* p = new Person(nam);
people.push_back(p);
cout<<nam<<endl;
}
cout<<"\nFilled vector, size = "<<people.size()<<endl;
for(int i = 0; i<NP; i++)
{
string temp;
fin>>temp;
cout<<"\nNow receiving "<<temp<<endl;
int togive, numgiving;
fin>>togive>>numgiving;
cout<<"\n"<<temp<<" is dividing "<<togive<<" among "<<numgiving<<" people"<<endl;
Person bob = *(people.at(i));
cout<<"hi bob"<<endl;
//(*people.at(i)).setorigbalance(togive);
cout<<"Original balance set"<<endl;
int giveeach = togive/numgiving;
cout<<"or "<<giveeach<<" to each person"<<endl;
int giveself = togive%numgiving;
cout<<"and "<<giveself<<" to himself :/"<<endl;
people.at(i) -> setbalance(giveself);
for(int j=0; j<numgiving; j++)
{
string nametogiveto;
fin>> nametogiveto;
cout<<nametogiveto<<endl;
for(int k=0; k<NP; k++)
{
string namy = people.at(k)->getname();
if(namy==nametogiveto)
{
cout<<"\nHere you go "<<namy<<" have "<<giveeach<<endl;
people.at(k)->setbalance(giveeach);
people.at(i)->setbalance(-giveeach);
break;
}
}
}
}
for(int i=0; i<NP; i++)
{
cout<<people.at(i)->getname()<<endl;;
cout<<people.at(i)->getorigbalance() - people.at(i)->getbalance()<<endl;
cout<<endl;
fout<<people.at(i)->getname();
fout<<people.at(i)->getorigbalance() - people.at(i)->getbalance()<<endl;
}
return 0;
}
You're running into undefined behavior due to dereferencing null pointers.
vector<Person*> people(NP);
This line creates the vector with NP null pointers. You later add on your actual pointers but only ever access the first NP elements which are the null pointers.
That said you don't even need pointers here and I'd recommend getting rid of them. In fact you have memory leaks due to allocating pointers with new but never calling delete on them. In my experience it's typical for people just starting out with C++ to overuse pointers, so think about ways to avoid them first.
Change
vector<Person*> people(NP);
to
vector<Person> people;
and fill it using:
for(int i = 0; i<NP; i++)
{
string nam;
fin>>nam;
Person p(nam); // no more need for pointer or new here
people.push_back(p);
cout<<nam<<endl;
}
later when accessing it you don't need any dereferencing anymore either. That means you can get rid of all the * for example:
Person bob = *(people.at(i));
turns into:
Person bob = people.at(i);
and you can access member functions with . instead of -> everywhere, for example:
people.at(k)->setbalance(giveeach);
would turn into:
people.at(k).setbalance(giveeach);
This means getting rid of a lot of unneeded dereferencing of pointers and also of the memory leak you previously would have had.
For me, it seems that you are getting that error since opening input file fin is not successful. To check it, add the following line after you define fin variable:
ifstream fin ("gift1.in");
if(!fin) {
cout << "Error opening input file.\n";
}
In any case, it's always a good practice to check if the file is opened successfully.

crash with "glibc detected: vector double free or corruption (out)"

I am implementing a permute function for integers. it has run time error of
"vector double free or corruption (out)".
With gdb, after step by step calling, it crashes after the iteration finishes.
But I really struggle to find out where the problem is.
#include <vector>
using namespace std;
class Permute {
public:
vector<vector<int> > vv;
// interface
vector<vector<int> > permute(vector<int> &num) {
vector<int> v(0);
doPermute(v, num);
return vv;
}
// recursive function to permute
void doPermute(vector<int> v, vector<int> &num) {
if(num.empty()) {
vv.push_back(v);
// on gdb, if next after the above one, it is fine,
// but crashes after the following next
} else {
for (int i = 0; i < num.size(); i++)
{
int toAdd = num[i];
vector<int> rest(num);
rest.erase(num.begin()+i);
vector<int> prefix(v);
prefix.push_back(toAdd);
doPermute(prefix, rest);
}
}
}
};
int main(){
Permute pInst;
// sample to test with {1}
vector<int> vt (1, 1);
pInst.permute(vt);
}
Take a look at this line:
rest.erase(num.begin()+i);
Try to use the proper iterator for erase:
rest.erase(rest.begin()+i);

Vector push_back causing Unhandled exception

Everything is working until the compiler tries to perform the push_back operation.
in the if condition proper values are being returned.
I have declared items as:
vector<int> items; // inside the header file.
//inside the .cpp file
void MsPs::findnSort()
{
for(int i = 1; i<50 ; i++)
{
string temp = static_cast<ostringstream*>( &(ostringstream() << i) )->str(); // TO convert int i to a string temp
if(findSupport(temp) >= MIS[i])
{
items.push_back(i);
}
}
}
the following error pops up:
Unhandled exception at 0x5052ad4a (msvcp100d.dll) in PrefixScan.exe: 0xC0000005: Access violation reading location 0x3d4cccd1.
PS: I have one more function using the push_back operation and there it's working fine.
Can anyone help me with this?
Even this gives the same error:
void MsPs::findnSort()
{
for(int i = 1; i<50 ; i++)
{
items.push_back(i);
}
}
I think the issue is that the ostringstream is destructed when the static cast returns. Thus your pointer is dangling when str() is called. Try this instead:
void MsPs::findnSort()
{
for(int i = 1; i<50 ; i++)
{
ostringstream blah;
string temp = (blah << i).str();
if(findSupport(temp) >= MIS[i])
{
items.push_back(i);
}
}
}