0

My program collapse when I run it. If I comment out line if((str1->compare(*str2))==0 ){...} it works OK. I don't know how to compare two elements of string * which I create and delete after comparing.

main.cpp: In function `int operator==(const Integer&, const Integer&)':
main.cpp:18: warning: taking address of temporary
main.cpp:19: warning: taking address of temporary

Integer.h

class Integer {
public:
    Integer(int val, char *opis):m_val(val),m_opis(opis)
        {
            this->m_val = 0;
            this->m_opis = strdup("0");
        }

    friend int operator==(const Integer&,const Integer&);

      private:
        int m_val;
        char *m_opis;
}

main.cpp

    int operator==(const Integer&a, const Integer&b){
        string *str1 = &string ( a.m_opis );
        string *str2 = &string ( b.m_opis );

        if((str1->compare(*str2))==0 ){return 1 ;} //<- Here is my problem i think.

        delete str1;
        delete str2;

        return 0;
    }
}
//Objects and comparing

    Integer o1(15,"lala");
    Integer o2(150,"lala");
    Integer o3;

    cout<<o1==o2;
Steve Robillard
  • 13,445
  • 3
  • 36
  • 32
mathewM
  • 139
  • 1
  • 1
  • 14

1 Answers1

3

The problem is that str1 and str2 are dangling pointers, as the temporary objects to which they point no longer exist by the time str1->compare() is invoked: this is what the compiler is warning about.

Don't use dynamically objects here, use stack allocated objects:

string str1(a.m_opis);
string str2(b.m_opis);

Other points:

  • prefer to use std::string instead of char* (Integer.m_opis). Related What is The Rule of Three?
  • m_opis is being set twice in the constructor and all instances of Integer will have the same string "0" (same not meaning same buffer but same content). Ditto for m_val.
Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • If I use stack allocated objects, can I delete it after comparing or they stay in memory ? – mathewM May 22 '12 at 16:21
  • @mathewM, the stack allocated objects will be destroyed automatically when the function returns. – hmjd May 22 '12 at 16:22
  • `int operator==(const Integer&a, const Integer&b){ string str1(a.m_opis); string str2(b.m_opis); if((str1.compare(str2))==0 ){ return 1 ;} else return 0; }` This doesn't work now. – mathewM May 22 '12 at 16:32
  • @mathewM, you should post another question for this as it is unrelated to the crash which was the subject of this question. Asking another question will mean more people will look at it, and contribute to solving the issue. – hmjd May 22 '12 at 16:36