Dynamic Array Memory delete[] issue.

The assignment was to use a dynamic array to display the Fibonacci sequence backwards. Everything works except part of the assignment was to allocate and de-allocate elements. I tried to do this using the delete[] v; but it keeps triggering a break point and shows CrtIsValidHeapPointer error. I have no idea why its doing this and I'v tried playing around with my code to figure it out. I'm wondering if I allocated the elements wrong?

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//Use a local array of size 20 to store the sequence of numbers and then print the sequence in reverse order (largest number first);
//display 6 numbers per line and use 5 positions for each number;

//Your program should make sure that length the series (i.e., the int being passed to the Fibonacci function) is >= 2 and <= 20;
//otherwise your program should display a message that length is out of bounds and terminate the execution.

//one extra point if your program correctly allocates and deallocates a dynamic array for length elements instead of using a fixed size
//array of size 20 to hold the numbers in the Fibonacci series.

#include    <iostream>
#include    <iomanip>
using namespace std;

void Fibonacci(int);


int main( )
{
    cout << "how many numbers in the Fibonacci Series? ";

    int n;                          // n numbers in the Fibonacci Series
    cin >> n;

    Fibonacci( n );
	system("pause");
    return 0;
}

// the rest of your program...

void Fibonacci(int n)
{
	int *v = 0;
	int p;
	int l=0;
	int first = 1;
	int second = 1;
	v = new int[n-3];
		if(n>=2, n<=20)
		{
			v[0]=1;
			v[1]=1;
				for(int i=2; i<=n; i++)
				{
				p = v[i-2] + v[i-1];
				v[i] = p;
				}
			cout << n << " numbers of the Fibonacci sequence in reverse order: " << endl;
			
			while(n > 0, n--)
			{
					if(l < 6)
					{
						cout << v[n] << "     ";
						l++;
					}
					else if(l > 6 && l < 12)
					{
						cout << v[n] << "     ";
						l++;
					}
					else if(l > 12 && l < 18)
					{
						cout << v[n] << "     ";
						l++;
					}
					else if(l > 18)
					{
						cout << v[n] << "     ";
						l++;
					}
					else
					{
						cout << endl << v[n] << "     ";
						l++;
					}

			}

		}
		else
		{
			cout << "Please enter a number 2 from 20";
			exit(0);
		}
		cout << endl;
		delete[] v;

}
Lines 39 and 50 don't do what you think they do. Check your syntax.

What's the point of lines 52-76 if all the blocks do the same?
Consider the loop at line 43. The last time through the loop, i==n so line 46 does v[n]=p. But at line 38 allocates space for only n-3 elements, making the largest valid index n-4.
Topic archived. No new replies allowed.