I hope you're all having a good day! So I want to create a class which saves a word (string) as a character array. I allocated memory to str in the default constructor, not sure if that's how it works.
` #include <iostream>
using namespace std;
class String{
private:
char *str;
public:
String(){
str=new char[10];
str="Hello";
}
void getstr(){
for (int i=0;i<5;i++){
cout<<str[i];
}
}
~String(){
delete []str;
}
};
int main(){
String s1;
s1.getstr();
return 0;
}
When i run this program, it does print "Hello" but this is the exact output:
*** Error in `./main': free(): invalid pointer: 0x0000000000400ab5 ***
Hello
When i removed the destructor part, it worked fine,but i need to free the memory allocated to str,right? Any help?
Thanks in advance :)