lundi 4 mai 2015

Destructor causes segment fault when delete dynamic allocation of char type [duplicate]

This question already has an answer here:

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)

Aucun commentaire:

Enregistrer un commentaire