| incognito (65) | ||||
|
Hi, I am trying following program
At line 43, n2 goes out of scope. So ideally, destructor should get called for n2, that is, only once. But I see desctructor is called twice!. Not sure why. Could somebody please explain? Thanks in advance :) | ||||
|
Last edited on
|
||||
| Caligulaminus (171) | |
|
n1 and n2 both go out of scope on line 47. Everything is alright. Well not everything. I think you're leaking memory (n2.age is not freed). | |
|
Last edited on
|
|
| incognito (65) | |
| Modified the program. Still the same result. Agreed, both go out of scope at line 47..But shouldn't n2 go out of scope at line 44? That means destructor will get called twice for n2 and once of n1(at line 47), that is, total 3 times. But I still see destructor gets called only twice. | |
|
|
|
| Caligulaminus (171) | |
|
Now n2's destructor is called at line 44 and n1's destructor is called at line 48. Everything is fine(except for the memory leak). | |
|
|
|
| doug4 (224) | |
|
As Caligulaminus has said a couple of time, there is a memory leak. But the cause of your core dump is the related problem of you deleting the same memory twice. Because you did not define an assignment operator for class name, when you assign n2 to n1 (line 40), the default assignment operator is called, and all of the fields from n1 are copied into n2. That means that n2's old value of age is lost, and it now points to the array allocated by n1. So now, the 20-int array is leaked, and both n1 and n2 try to delete the 10-int array. Edit: fixed typo | |
|
Last edited on
|
|
| Caligulaminus (171) | |
|
Argh! Double delete - how could I miss that. m( | |
|
|
|
| incognito (65) | |
|
Thanks guys :). I deliberately did not define overloaded assignment operator because I wanted to see the effects of memory leaks :). Got the concept now ;) Cheers! | |
|
|
|