Memory allocation causing program to crash

For part of a homework assignment, I've been instructed to create a class to contain a vector which is constructed by default as a zero vector with 3 values. I'm just testing it out at an early stage to make sure everything works smoothly and I've found that constructing it with anything more than 6 elements causes the program to crash when I try to print to standard output. Here are my source files (header, definitions and test program):

Vector.h - http://pastebin.com/snn0NTKd
Vector.cc - http://pastebin.com/B2DwirVc
testvector.cc - http://pastebin.com/HV6U83tZ

The program prints the vector correctly but crashes...if anyone can provide some insight it'd be helpful.
Why post your code there? Have you any idea how inconvenient that is? And it offers not benefit to the users of this site when your post is archinved.

As to your problem, you allocate enough space for 3 ints and assign 7.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
using namespace std; 

class CVector
{
	private:
		int size; 
		int* m_col;
	public:
		CVector() { } 
		~CVector() { }  
		
		void Construct(int sz ) ; 
		void Set(int loc,  int val) ;
		void Print() ; 
};
CVector::CVector()
{
	size = 0 ; 
}
CVector::~CVector()
{
	delete []m_col;
}
void CVector::Construct( int sz ) 
{
	m_col = new int[sz];
	for( int i = 0 ; i < sz; i++)
	m_col[i] = 0;
}
void CVector::Set(int loc, int val )
{
	if ( loc > sz ) 
	{
		cout <<"\n Error out of bound Out of bound ";
		
	}
	else
	{
		m_col[loc] = val;
	}
		
}
void CVector::Print()
{
	for( int i = 0 ; i < size; i++)
	cout<<"\n The value of col = "<<m_col[i];
}
Topic archived. No new replies allowed.