Segmentation fault when trying to use class objects stored in a vector

I am not very experienced with C++, so advance apologies if this is a silly question.

I have made a vector of class objects. I have done this because each time I run the code, I may need a different number of objects. For example, if the objects are chemical elements, I will need different elements for different reactions. I read the following post from this site for guidance: http://www.cplusplus.com/forum/beginner/63543/

I seem to be able to create a vector of the class objects and compile the code. For example:

1
2
std::vector<Algorithm<double,2U> > algorithm; 
algorithm.push_back( Algorithm<double,2U>() ); 


But when I try to apply functions from the class "Algorithm" to each object (i.e., each element of the vector), I get segmentation faults. For example:

1
2
for ( int i = 0; i < nElements; i++ )
algorithm[i].SetSolver( new gauss ); 


Can anyone tell me what I'm doing wrong based on what I have provided? Thanks a lot.
How are you getting nElements?

Generally when you loop through a full vector, you use the size as the limit. There a chance you could be accessing elements of the vector that don't exist.

Apart from that, nothing springs out given that code, so that would be the first thing I'd check. However, it's entirely possible that the issue could be within your SetSolver function or gauss class.
Maybe something is wrong with the Algorithm class. Can it be copied/moved correctly?
closed account (ypfz3TCk)
Segmentation faults tend to stem from errors in addressing memory.
Last edited on
Thanks everyone for your help.

As written in the example I provided, I get nElements by reading in data from an external file. I wondered whether this might be a problem. So as a test, I specified nElements by doing a specified number of "push_backs" to add to the vector and then doing:

for ( int i = 0; i < algorithm.size(); i++ )

I still got the segmentation fault.

I'm pretty sure there is nothing wrong with the Algorithm or gauss classes because everything works fine when I only have one object of class Algorithm. The trouble I'm having is when I want to have an arbitrary number of Algorithm objects.
http://www.cplusplus.com/forum/general/112111/

> I'm pretty sure there is nothing wrong with the Algorithm or gauss classes
> because everything works fine when I only have one object of class Algorithm.
or your tests were not hard enough.

seeing new or delete should tingle your spider sense
Topic archived. No new replies allowed.