Dynamic Array

Oct 22, 2014 at 8:24pm
Im using microsoft Visual C++ and its giving me a HEAP errow how do I fix it?
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
#include <iostream>
using namespace std;
int main(){
	
    int num;
    int size = 2;
    int index = 0;
    int *listDyn = new int[size];
	
    do{
    cout << "Enter a number to add to the array or -1 to exit: " << endl;
    cin >> num;
    
	if(num == -1){
        continue;
    }
    if(index > size){

        int *listDynNew = new int[size *= 2];
        for(int i = 0; i < size; i++){

            listDynNew[i] = listDyn[i];


        }
		
        delete listDyn;
    }
	
    listDyn[index] = num;
	
    if(index == size-1){
        cout << "The arrays are full: ";
        for(int i = 0; i < size; i++)
            cout << listDyn[i] << " ";
            cout << endl;

    }
    index++;

    }while(num != -1);
	
    for(int i = 0; i < index; i++){
        cout << i+1 << " number is: "<< listDyn[i] << endl;

    }
	system("pause");
	return 0;
}
Oct 22, 2014 at 8:30pm
You are... Well, doing a lot of things wrong. FOr example, how can line 30 run if the if statement on 17 performs the required operations? listDyn is deleted, so how can it hold elements?
Oct 22, 2014 at 8:53pm
I got it to work Thanks.
Last edited on Oct 22, 2014 at 9:02pm
Oct 22, 2014 at 9:07pm
In lines 17-28 you're attempting to allocate a new larger array. That's fine, but what you're missing is assigning the new array to the old pointer.

After line 27:
1
2
 
  listDyn = listDynNew;


As you have it, you have two problems.
1) A memory leak. the pointer to listDynNew (line 19) goes out of scope at line 28, so you've lost addressibility to the new, larger array.
2) Illegal memory reference. You delete listDyn at line 27, then attempt to reference the memory you just deleted at line 30.
Topic archived. No new replies allowed.