Duplicate (conceptually):
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
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
#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< return out;
}
main.cpp
#include
#include "stringme.h"
using namespace std;
int main() {
StringMe a;
a = "Tran Viet Ha";
cout< StringMe b;
cout<<"Enter a string: ";
cin>>b;
cout<}
And error when execute:
Error in `./main': free(): invalid pointer: 0x08048beb ***
Aborted (core dumped)
No comments:
Post a Comment