Here is the code which I am trying to use, its compiling but giving unexpected results in turbo c++, but the program crashes in dev C++ , after some trial and error, I have found out that the keyword delete is causing the problem, but I am not able to find out how to correct the error. Can somebody find out the error in the program and explain it to me. Also, can somebody tell me how to write the same code using smart pointers?
Here is the code:
#include<iostream.h>
#include<process.h>
class list1
{
public:
virtual void getdata()
{ }
virtual ~list1()
{
cout<<endl<<"Destructor list1 called " ;
}
virtual void display()
{ }
};
class list2: public list1
{
public:
int data;
void getdata()
{
cout<<endl<<"Enter the data " ;
cin>>data ;
}
void display()
{
cout<<endl<<data ;
}
~list2()
{
cout<<endl<<"Destructor list2 called" ;
}
};
int main()
{
list1* ptr[3]; //array of pointers
char ch = 'y';
int n = 0;
while(ch=='y')
{
ptr[n] = new list2 ;
ptr[n]->getdata() ;
n++ ;
cout<<endl<<"Do you want to enter more of data " ;
cin>>ch ;
cout<<endl<<"The no of items currently added are: "<<n ;
}
ch='y';
while(ch=='y')
{
delete ptr[n];
n--;
cout<<endl<<"Item deleted " ;
cout<<endl<<"Do you want to delete more elements " ;
cin>>ch ;
cout<<endl<<"The no of items currently in the list are "<<n ;
}
int i = 0;
while(i < n)
{
ptr[i]->display() ;
i++ ;
}
cout<<endl ;
system("pause") ;
return 0;
}
You aren't bounds checking.
list1* ptr[3];
ptr has a maximum of 3 elements, if you put more in, you have the possibility of stomping on other things. (Who knows what is just after your array?)
while(ch=='y')
{
delete ptr[n];
And the same with this. If you press y more times than for delete than you pressed for create you'll be deleting things before the start of the array, and who knows what is there? It's probably invalid pointers, and that's what will be causing your runtime errors.
EDIT
What I said is a problem, but Nikos C. has the correct answer.
delete ptr[n]
will access uninitialised memory. You need to decrement before deleting
So if you press y to allocation once n will be 0 and be put in ptr[0], but when you press y to deallocate n will be 1 and ptr[1] will be deleted which is unallocated.