View Single Post
Old Apr 20th, 2006, 3:57 PM   #3
Cache
Hobbyist
 
Join Date: Sep 2005
Posts: 261
Rep Power: 4 Cache is on a distinguished road
The seg fault is caused by a1 and b1 being used to index an array before they have been initialized to a value within the valid range.

Here is a vector version of your code. I've not changed any logic, so if the output isn't what you expected, that's your fault

#include <iostream>
#include <vector>

using namespace std;

// TODO: Const correctness.

double f1(int a, double arg2);

int main()
{
	try
	{
		// a1 and b1 must be initialized to some number
		// withing the bounds of vecNum.
		int a1 = 0, b1 = 0;
		vector<double> vecNumTot( 6, 0 );

		f1( a1, 1.0 );
		f1( b1, 2.0 );
		
		// sum of 2 vector element by element
		vector<double>::iterator i = vecNumTot.begin();
		for( int j = 0; i != vecNumTot.end(); ++i, ++j )
		{
			*i = f1( a1 , 1.0 ) + f1( b1, 2.0 );
			cout << "vecNumTot[" << j << "]: " <<  *i << endl;
		}
	} catch ( std::out_of_range& )
	{
		// TODO: Error hadnling.
		
		// NOTE: This try/catch block isn't needed if
		// there's no chance a1/b1 are passed to
		// f1 with a value exceeding vecNum.end().
	}
	
	cin.get();
	return 0;
}

double f1( int a, double arg2 )
{
	vector<double> vecNum( 6, 0 );

	// place 6 numbers in int vector vecNum1
	vector<double>::iterator i = vecNum.begin();
	for( int j = 0; i != vecNum.end(); ++i, ++j )
	{
		*i = j + arg2;
		cout << "vecNum[" << j << "]: " << *i << endl;
	}
	
	// If 'a' is out of range, an exception will
	// be thrown.
	return vecNum.at( a );
}
Cache is offline   Reply With Quote