-5

I'm having problems with these three parts of codes, in the terms of Memory Allocations. I haven't got it yet.

Could you please point out to me what I am doing wrong and how I should go on correcting it?

1:

class MyString {
public:
    MyString()  : str(0) {}
    MyString( char *a ) 
    { str = new char[strlen(a)+1]; strcpy(str,a); }
    ~MyString() { delete[] str; }
private:
    char *str;
    friend ostream& operator<<(ostream &os, const MyString &str);
};

ostream& operator<<(ostream &os, const MyString &s)
{
    return os  << s.str  << endl;
}

int main()
{
    MyString str("Mitt namn");
    MyString *strp = &str;
    // alot of code
    delete strp;
    // alot of code
}

2: Defined as above

int main()
{
    MyString *str1 = new MyString("Mitt namn");
    MyString str2  = *str1;
    delete str1;
    // alot of code
    cout << str2 << endl;
}

3: Still defined as above

class MyASCII : public MyString {
public:
    MyASCII( char *a) : MyString(a), ascii(0)
    { 
        if (a==0) return;
        ascii = new int[strlen(a)];
        for (int i=0; i<strlen(a); i++)
            ascii[i] = int(a[i]);
    }
    ~MyASCII() { delete[] ascii; }
private:
    int *ascii;
};
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
Stabbah
  • 73
  • 10

2 Answers2

4

Firstly, just use std::string. Secondly, Rule of Three violation. Thirdly, you delete a local variable in 1's main, which is wrong.

Puppy
  • 144,682
  • 38
  • 256
  • 465
2
  1. C++ has a built in string class, std::string, why don't you use it?

  2. Your assignment semantics are broken. You need an assignment operator and a copy constructor that copy the memory held by str.

    In C++ it's essential to have consistent copy-constructor, assignment and destructor. This is the Rule of three DeadMG referred to. You should read the related question What is The Rule of Three?

    When copying MyString, your code makes a shallow copy. So both instances share the same data. Once you destroy the first instance, the second one has a dangling pointer.

  3. Your code sample 1 assigns a pointer to a local variable to strp and then tries to delete it. You can only free memory that was allocated with new MyString(...) with delete.

    The destructor of local variables are destroyed automatically once they pass out of scope. You don't need to (and can't) free them manually with free.

  4. Code sample 2 would be fine, if your class were implemented correctly. It uses the copy constructor to copy the heap allocated string to a local variable. But since your copy contructor doesn't actually copy the memory, it's broken as well.

Community
  • 1
  • 1
CodesInChaos
  • 106,488
  • 23
  • 218
  • 262