0

This is my code that adds two times.

This is the error message it gives -

Error message

It says =

q3(1483,0x105404580) malloc: *** error for object 0x600003904070: pointer being freed was not allocated q3(1483,0x105404580) malloc: *** set a breakpoint in malloc_error_break to debug

I did plenty number of checks and tried multiple things but everytime it doesn't works.

If I remove the destructor then its working otherwise the code is not working and always throwing the same bug!

This is my source code to add two times =

#include <iostream>
using namespace std;

class Time{
    int *min,*hour,*sec;
    
    public:
    Time(){
        min = new int;
        hour= new int;
        sec = new int;

        *min = 0;
        *hour = 0;
        *sec = 0;
    }

    void input(){
        cin>>*min>>*hour>>*sec;
    }
    friend void add(Time,Time);

    void display(){
        cout<<"The sum is = "<<"Min = "<<*min<<"Sec = "<<*sec<<"Hour = "<<*hour;
    }

    ~Time(){
        delete min;
        delete hour;
        delete sec;
    }
};

void add(Time t1,Time t2){
    Time t;
    *t.sec = *t1.sec + *t2.sec;
    *t.min= *t1.min + *t2.min;
    *t.hour = *t1.hour + *t2.hour;
    
    if(*t.sec>60){
        *t.min = *t.min + *t.sec /60;
        *t.sec = *t.sec % 60;
    }

    if(*t.min>60){
        *t.hour = *t.hour + *t.min /60;
        *t.min = *t.min % 60;
    }

    t.display();
}

int main(){
    Time t1,t2;

    cout<<"Enter value of 1st time = ";
    t1.input();

    cout<<"Enter value of 2nd time = ";
    t2.input();


    add(t1,t2);

    return 0;
} 
Arjun Ghimire
  • 301
  • 1
  • 2
  • 8
  • 2
    May I ask why youre using pointers to dynamically allocated ints instead of just 3 ints? the entire code would be so much simpler... – Borgleader May 07 '22 at 15:52
  • 2
    As for your bug, your copy ctor is copying the pointers, so when you pass a Time object to add() by value it will make a copy for tht function, that copy will then be destroyed at the end of the function, thus deleting the pointers, when you reach end of main the original will also be destroyed but contains a (now dangling) pointer which causes the crash. You need to implement 'deep' copy yourself, or use std::unique_ptrs (or better yet as i alluded to earlier, not use pointers at all as they seem pointless in this case) – Borgleader May 07 '22 at 15:54
  • @Borgleader yes it would be simple using only int but my teacher give me the requirement of doing this using friend function and dynamic constructor because of that I have to do with this method. – Arjun Ghimire May 07 '22 at 22:32
  • Thank you @Borgleader, Can you please help me correcting that code? What I have to implement to correct the code? – Arjun Ghimire May 07 '22 at 22:45
  • When I modify my code like this = void add(Time &t1,Time &t2){ Then its working, But I don't understand how its working! – Arjun Ghimire May 07 '22 at 23:06

0 Answers0