You are here:

C++/what is wrong with this?



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:

using namespace std;

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

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
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.


All Answers

Answers by Expert:

Ask Experts




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.


about 15 years or so

post graduate engineer

©2017 All rights reserved.