You are here:

C++/what is wrong with this?

Advertisement


Question
Hello,

i am not sure but could it be that i already deleted the memory to store the object cuz i cant figure out the error in this code:



#include<iostream>
#include<cstdlib>
using namespace std;

class dyna{
     int *p;
     public:
         dyna(int i);
         ~dyna(){free(p); cout<<"freeing\n";}
         int get(){return *p;}
         };
     dyna::dyna(int i){
         p = (int*)malloc(sizeof(int));
         if(!p){
         cout<<"allocation failure\n";
         exit(1);
         }
         *p = i;
         }
     
     //return a negative value of *ob.p
     int neg(dyna ob)
         {
         return -ob.get();
         }
     
     
     int main(){
         
         dyna o(-10);
         cout<<o.get()<<"\n";
         cout<<neg(o)<<"\n";
         
         dyna o2(20);
         cout<<o2.get()<<"\n";
         cout<<neg(o2)<<"\n";
         
         dyna o(-10);
         cout<<o.get()<<"\n";
         cout<<neg(o)<<"\n";
         
         return 0;
         }   
         
   ps: please, abit concise explanation will do cuz i have been on this all day.. thanks


Answer
The function   

     int neg(dyna ob)

takes its parameter by value, it gets a copy of the original object. The pointer p in this copy is the same as that in the original. When the function returns, this copy is destroyed, releasing the memory pointed to by p. The original object is now in an invalid state - its p points to memory that has already been released.

To fix this error, rewrite the function as

     int neg( const dyna& ob)

Now, since the function takes its parameter by reference, a copy is not made.

You may need to make copies in other places, so the technically correct thing to do is to write a 'copy constructor'. see http://cplus.about.com/od/learning1/ss/constructors_6.htm
If you find it hard to follow, read the tutorial from the beginning.

Also, in C++, prefer using new and delete over malloc and free.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.