![]() |
| | #1 |
| Registered User Join Date: Mar 2009
Posts: 35
| Crash in destructor Please let me know why it is crashing in destructor: //Simulation of smart pointer Code: #include<iostream.h>
class smartpointer
{
public:
int *p;//ordinary pointer
public:
smartpointer(int n)
{
p =new int[n];
int *t =p;
for(int i=0;i<n;i++)
*t++=i*i;
}
int* operator++(int)
{
return p++;
}
int operator*()
{
return *p;
}
~smartpointer()
{
if(p)
delete [] p;
}
};
void main()
{
smartpointer sp(10);
for(int i=0;i<10;i++)
cout<<*sp++<<endl;
}
|
| vaibhavs17 is offline | |
| | #2 |
| Kiss the monkey. Join Date: Sep 2001
Posts: 810
| Ensure that p is initialized to 0. The problem, it seems, is that your ++() returns p++, which is a temporary with the value of one past the address to which p refers. Thus *p++ is problematic, since the pointer p++ might not exist anymore.
__________________ "If you tell the truth, you don't have to remember anything" -Mark Twain |
| CodeMonkey is offline | |
| | #3 |
| Registered User Join Date: Mar 2009
Posts: 35
| so how can we delete the allocated memory in dTOR? |
| vaibhavs17 is offline | |
| | #4 |
| Algorithm Dissector Join Date: Dec 2005 Location: New Zealand
Posts: 2,476
| There are many problems with that class. Listing them from biggest to smallest problem:
__________________ My homepage Advice: Take only as directed - If symptoms persist, please see your debugger |
| iMalc is offline | |
| | #5 | |
| Mysterious C++ User Join Date: Oct 2007
Posts: 14,099
| Furthermore, the code is not indented. Indent! Plus it uses void main. Use int main.
__________________ Using: Microsoft Windows™ 7 Professional (x64), Microsoft Visual Studio™ 2008 Team System I dedicated my life to helping others. This is only a small sample of what they said: "Thanks Elysia. You're a programming master! How the hell do you know every thing?" Quoted... at least once. Quote:
| |
| Elysia is offline | |
![]() |
| Tags |
| code |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Destructor crash | Abbygail | C++ Programming | 1 | 05-25-2009 07:31 PM |
| Destructor being called on SGI hash_map key | cunnus88 | C++ Programming | 4 | 02-11-2009 12:05 AM |
| exception in the destructor | coletek | C++ Programming | 3 | 01-12-2009 12:01 PM |
| Can you call a constructor within a destructor, or vise vesa? | meili100 | C++ Programming | 1 | 06-10-2008 08:38 PM |
| destructor question | kocika73 | C++ Programming | 3 | 03-10-2006 11:29 AM |