I keep getting a Segmentation fault error when i run my program, i read that this is an error with memory or somthing, i was hoping someone could point out where the problem in my program is. My code is below.

#include <iostream>
#include <vector>

using namespace std;

class sequence
{

public:
        void read();

        int print(vector<int>&) const;

        int getelement(sequence x,int i);

        sequence();

        sequence(int s);
private:
        int next;

        vector<int> v2;
};





int main(){
        sequence x;
        x.read();
        int element;
        int i;
        cout << "please enter the element you would like returned." << endl;
        cin >> i;
        element = x.getelement(x,i);
        return 0;
}

sequence :: sequence()
{



}
sequence:: sequence(int s)
{
        vector<int> v2(s);

}
void sequence::read()
{
        vector<int> v2;
        int s;
        cout << "Enter the number of integers" << endl;
        cin >> s;
        cout << "Enter your sequence, place a negative number at end." << endl;
        cin >> next;

        while(next > 0)
        {

                v2.push_back(next);
                cin >> next;
        }
         for(unsigned int i = 0; i < v2.size(); i++)
        {
                cout << v2[i];
        }


}
int sequence::print(vector<int>&)const
{


        for(unsigned int i = 0; i < v2.size(); i++)
        {
                cout << v2[i];
        }
}
int sequence::getelement(sequence x,int i)
{
        int a;
        return x.v2[a];
}

Recommended Answers

All 2 Replies

what compiler are you using?
Most compilers allow a step through compilation process where you can compile a line of code at a time. This is useful as when it gets to a line with an error it will tell you and BAM theres your problem!

Seg faults are usually caused when you access memory that doesnt belong to you.
Example : an array
char ARRAY[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << ARRAY [25];
will seg fault as your accessing a part of memory that doesnt belong to your program.

I dont know for sure but id recommend commenting out your print function as it has a for loop that may be accessing memory that is not assigned to your program! But definently go look debugger commands if ur using linux g++
or google how to compile step by step with your compiler

Use code tags.

Probably your problem is in void sequence::read() method. You store some data to local vector<int> v2, then you try to read from sequence::v2, but this is completly another vector. And since it's not populated, you get seg fault.
There are some other issues in code. You shuold get good book about OO programming.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.