-5

I'm making my own string class but I got a problem reading the characters of the string while using strlen() to do that.

/****str.h****/

class str
{
private:
    char *m_ptr;
    unsigned int m_size;
    //unsigned int m_capacity;
public:
    str();
    str (const char *);
    str (const str &);
    ~str (){if (m_size != 0) delete [] m_ptr;};
    char *data() {return m_ptr;};

    //Sobrecarga de operadors.
    str operator=(str);
    friend std::ostream& operator<<(std::ostream &, str);
};

I got the error using the constructor initialized with a c-string constant.

/****str.cpp****/

//Default constructor.
str :: str ()
{
    m_ptr = new char [1];
    m_ptr[0] = '\0';
    m_size = 0;
    //m_capacity = 10;
}

str :: str(const char *sm_ptr)
{
    m_size = strlen(sm_ptr); //HERE IS WHERE THE ERROR OCCURS.
    m_ptr = new char[m_size + 1];
    strcpy(m_ptr, sm_ptr); //Copies the C string pointed by source into the array pointed by destination, including the terminating null character 
}
//Copy constructor.
str :: str(const str &right)
{
    m_ptr = new char [right.m_size];
    strcpy (m_ptr, right.m_ptr);
    m_size = right.m_size;
}

str str::operator=(str right)
{
    if (m_size != 0) delete [] m_ptr;
    m_ptr = new char [right.m_size + 1];
    strcpy(m_ptr, right.m_ptr);
    m_size = right.m_size;
    return *this;
}

std::ostream &operator<<(std::ostream &strm, str obj)
{
    strm << obj.m_ptr;
    return strm;
}

0x0053fdd0 {m_ptr=0xcccccccc m_size=3435973836 } str *

blackout
  • 84
  • 9
  • 3
    Welcome to Stack Overflow. Please read [Stack Overflow: How to ask](http://stackoverflow.com/questions/how-to-ask) and [Jon Skeet's Question Checklist](http://msmvps.com/blogs/jon_skeet/archive/2012/11/24/stack-overflow-question-checklist.aspx) to find out how to ask a good question that will generate good useful, answers. – Our Man in Bananas Jul 08 '14 at 09:37
  • _'I got the error using ...'_ which error in particular? Edit your question please. – πάντα ῥεῖ Jul 08 '14 at 09:40

1 Answers1

1

Changing the assignment operator declaration to

str& operator=(str&);

or even

const str& operator=(const str&);

would eliminate creation of temporary objects. Check out this article for more information on passing arguments to functions.

There are a couple of other issues. For example in default constructor you allocate memory but you don't set size so it's never going to be freed. Also, in copy constructor and assignment operator it's almost always a good idea to check for self-assignment.

Anton
  • 1,183
  • 10
  • 19