problem when trying to delete array off the heap

Here is my code:

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
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <vector>
#include <sstream>
#include <fstream>
#include <iostream>

using namespace std;

int main()
{

	//open file
	
	ifstream myfile;
	
	myfile.open("proj2.txt");
	
	if(myfile.fail())
	{
	
		cout << "Unable to open file";
		
		exit(1); //exit program
	
	}//end if
	
	int num = 0; //initialize number
	
	//declare vector
	
	vector<int> vec;
	
	while(myfile >> num)
	{
	
		//append number to the vector
		
		vec.push_back(num);
		
	}//end while
	
	//declare array with size of the vector
	
	int *arr = new int[(vec.size()-1)]; //must be declared on the heap for we don't know the size
	

	//load array with data from text file
	
	for(int i = 0; i < vec.size(); i++) //problem is in here somewhere
	{
	
		arr[i] = vec[i]; //put the i'th value of the vector into the i'th value of the array
				
			
	}//end for

	myfile.close();

	delete [] arr; //where the error comes in

	return 0;
}//end main 


I was able to isolate the problem to the loop I placed a comment at. If I comment that part out it works. Also, if I leave the last element empty in the array it works. Not sure what's going on here. Any help would be greatly appreciated.

There is no error code, it compiles fine, but crashes when I delete arr off the heap.
On line 43. You've set arr's size to be one less than vec's.
Ah... duh... Thanks thus far! Okay similar problem. And this is going off the code above:

The user deletes an item from the array (n).

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
		n = n - 1; // compensate for the index starting at 0

		vec.erase(vec.begin() + n);

	//delete array element

		//first shift everything accordingly
		//start at i = n, and then end at vector length
		for(unsigned int i = n; i < vec.size(); i++)
		{

			arr[i] = arr[i+1];

		}//end for


		//save the address of the memory arr is refrencing

		int* savedAddy = arr;

		//allocate some memory for an array with size (n-1)

		arr = new int[vec.size()-1]; //the size has been decreased by 1

		//copy the contents to the new array

		for(unsigned int i = 0; i < vec.size()-1; i++)
		{

			arr[i] = savedAddy[i];

		}//end for

		delete [] savedAddy;
Topic archived. No new replies allowed.