member function constructor takes an int into a vector

Nov 5, 2010 at 6:32pm
hi,
what i'm trying to do is to make a constructor in a class, which takes in an integer and creates a vector one element long of type int and puts the int into it. this is what i've done:
1
2
3
4
5
Intclass::Intclass(int x)
	{
	vector <int> val(1,x);
	cout << val[0] << endl;
	}

this compiles and the program runs until the end of this function (after the cout line) after which I get a segmentation fault.
I gather that this is something to do with it trying to access protected memory, though I've got no idea why, or how to fix it. I'm on Linux Mint if that important (will this still happen if compiled on windows?).
thanks in advance for any and all replies.
afrg

ps. I know that this is my second query today, I promise that i do google (or scroogle) before posting, yet what is actually wrong here is being evasive.
Nov 5, 2010 at 6:42pm
That piece of code is fine, so the error must be somewhere else.
A segmentation fault happens if you try to access memory that does not belong to your process which usually is because you try to dereference a pointer that doesn't point to a valid object.
Last edited on Nov 5, 2010 at 6:43pm
Nov 6, 2010 at 3:55pm
thanks, i found where the segmentation fault was, and indeed it was not in that function.
i think it appears to be somewhere here:
1
2
3
4
5
6
7
8
9
10
string Intclass::strg() const
	{
	string s;
	for (int i = 0; i < val.size(); ++i)
		{
		s += val[i];
		}
	cout << s <<" x" << endl;
	return s;
	}

as when i comment this out it dissapears.
Topic archived. No new replies allowed.