error: command don't work

hi everyone. I'm study c++ and I wrote a short code but it didn't work exactly.
Every command under "demo(f);" not work. I don't understand why it's so. Please help me!

here my code(i wrote in ubuntu):

#include <iostream>
#include <string.h>
#include <ncurses.h>
using namespace std;
class F{
string*s;
public:
F(string* g){
s=g;
}
~F(){delete []s;}
};

void demo(F f){}
int main(int argc, char **argv){
initscr();
string a[]={"hello 1","hello 2", "hello 3"};
F f(a);
demo(f);
cout<<a[2]<<endl;
getch();
endwin();
return 0;
}
Last edited on
Your 'F' class will delete[] the pointer it owns in its destructor. This means that whatever pointer you give it in the ctor absolutely must point to something allocated with new[]. You are not doing this. So when 'f's dtor is run at the end of the 'demo' function is run, you are attempting to delete data that cannot be deleted.

If that's not clear, let me try and break it down step by step:

 
string a[]={"hello 1","hello 2", "hello 3"};

This creates a fixed-size array named 'a'. That array is not dynamically allocated with new[].... therefore it will be automatically cleaned up and must not be deleted.

 
F f(a);

This constructs an 'F' object named 'f', and gives it a pointer to 'a'. So now 'f::s' points to the 'a' array.

At this point you are already screwed, because when 'f' is destroyed, it will delete[] s... and since s points to a, it will delete a... but a cannot be deleted because it was not created with new!


The problem goes into the 'demo' function call, but really the main problem here should be clear.

Typically classes should not delete[] something they do not own. And the only real way to ensure ownership is to have them allocate it themselves.

Honestly, you should just avoid new/delete altogether until you understand pointers a bit more. You probably do not have any real need for them.
Now, I understood this problem. Thank you very much!
Topic archived. No new replies allowed.