fasoulas
October 12th, 2010, 08:41 PM
I think i have a memory leak in this code and i need your help
In the increaseby function i copy the contents of the old array to the new one and return the pointer to the new array.
Will the contents of the old array stay in the heap??
#include <iostream>
using namespace std;
//finds array average
double find_avg(int* arr,int size);
//increase the size of the array
int* increaseBy(int* a,int size,int inc);
void main()
{
//variables
int size;
//array size
cout << "Enter array size : ";
cin >> size;
//allocate mamory for new array
int* arr = new int[size];
//enter values
cout << "Enter values: ";
for(int i=0;i<size;i++)
cin >> arr[i];
///////////////////////////////////////
int new_size;
cout << "\nEnter new size: ";
cin >> new_size;
arr = increaseBy(arr,size,new_size);
///////////////////////////////////////
//deallocate memory
delete[] arr;
system("pause");
}
//increase the size of the array
int* increaseBy(int* a,int size,int inc)
{
//allocate mamory for new array
int *p =new int[size+inc];
//copy values from old array
for(int i=0;i<size;i++)
p[i]=a[i];
//deallocate old memory
delete[] a;
//return new array location
return p;
}
I know that this could be implemented with vectors but i do just to have a better understanding of pointers
In the increaseby function i copy the contents of the old array to the new one and return the pointer to the new array.
Will the contents of the old array stay in the heap??
#include <iostream>
using namespace std;
//finds array average
double find_avg(int* arr,int size);
//increase the size of the array
int* increaseBy(int* a,int size,int inc);
void main()
{
//variables
int size;
//array size
cout << "Enter array size : ";
cin >> size;
//allocate mamory for new array
int* arr = new int[size];
//enter values
cout << "Enter values: ";
for(int i=0;i<size;i++)
cin >> arr[i];
///////////////////////////////////////
int new_size;
cout << "\nEnter new size: ";
cin >> new_size;
arr = increaseBy(arr,size,new_size);
///////////////////////////////////////
//deallocate memory
delete[] arr;
system("pause");
}
//increase the size of the array
int* increaseBy(int* a,int size,int inc)
{
//allocate mamory for new array
int *p =new int[size+inc];
//copy values from old array
for(int i=0;i<size;i++)
p[i]=a[i];
//deallocate old memory
delete[] a;
//return new array location
return p;
}
I know that this could be implemented with vectors but i do just to have a better understanding of pointers