1

Duplicate (conceptually):

What is The Rule of Three?


I'm working on my class, StringMe for my homework. I make it work like C++ standard library, string, but in destructor, using delete causes segment fault, it happens in Linux (I'm using Ubuntu) only, in Windows it seems fine when executing. Here's my code.

stringme.h

#ifndef STRINGME_H
#define STRINGME_H

#include <iostream>

using namespace std;

class StringMe {
    char *data;

    public:
        StringMe();
        ~StringMe();
        StringMe operator =(char*);
        friend istream& operator >>(istream&, StringMe&);
        friend ostream& operator <<(ostream&, StringMe);
};

#endif

stringme.cpp

#include <iostream>
#include "StringMe.h"

StringMe::StringMe() {
    // initializing empty string
    data = new char[256]();
}

StringMe::~StringMe() {
    delete[] data; //error here
}

StringMe StringMe::operator = (char* str) {
    data = str;
}

istream& operator >>(istream& in, StringMe &str) {
    in.getline(str.data, 256);
    return in;
}
ostream& operator <<(ostream& out, StringMe str) {
    out<<str.data;
    return out;
}

main.cpp

#include <iostream>
#include "stringme.h"

using namespace std; 

int main() {
    StringMe a;
    a = "Tran Viet Ha";
    cout<<a<<endl;
    StringMe b;
    cout<<"Enter a string: ";
    cin>>b;
    cout<<b<<endl;
}

And error when execute:

Error in `./main': free(): invalid pointer: 0x08048beb *** Aborted (core dumped)

Community
  • 1
  • 1
mozart
  • 89
  • 7
  • Learn about Rule of Three (and Five). – Nawaz May 04 '15 at 18:26
  • @Nawaz Come on now, [The Rule Of *Three*](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). That duplicate won't even help him in the slightest. – 0x499602D2 May 04 '15 at 18:28
  • @0x499602D2: Added both. :D – Nawaz May 04 '15 at 18:29
  • 3
    The primary cause of your problem is that you are attempting to release memory that may not be even writtable. It's the string literal, it is statically allocated by the compiler and as such it's typically readonly and not on heap (thus allocator doesn't even know what it is). (Obviously, Windows/Windows compiler let you delete memory of string literals.) – Werkov May 04 '15 at 18:34
  • so `data = new char[256]()` in constructor is not dynamic allocation? – mozart May 05 '15 at 04:59

0 Answers0