开发者

Memory allocation problem when creating a class C++

Still learning C++, and still having specific errors :). I have an object of the following composition:

class document {
private:
    char *denumire;
    char *tema;
    char *autorul;
    int num_pag;
    data last_edit;
public:
    document();
    document (const char *s1,const char *s2,const char *s3, int i1, data d1);
    document (const document&);
    document (const char *s1);
    ~document ();
    void printdoc(void);
    void chden(char *s);
    void chtema(char *s);
    void chaut(char *s);
    void chnumpag(int n);
    void chdata(data d);
};

The problem is that when I try to initialize it with the following constructor, I get segmentation fault:

document::document (char *s1, char *s2, char *s3, int i1, data d1) {
    denumire=new char[strlen(s1)+1];
    strcpy(denumire,s1);
    tema=new char[st开发者_运维问答rlen(s2)+1];
    strcpy(tema,s2);
    autorul=new char[strlen(s3)+1];
    strcpy(autorul,s3);
    num_pag=i1;
    last_edit.an=d1.an;
    last_edit.luna=d1.luna;
    last_edit.zi=d1.zi;
    cout <<"Setarea documentului finisata\n";
}

As much as I understand, all the variables are assigned correctly, because the message "Setarea documentului finisata" appears, and after that the segfault appears. All the code compiles fine, without any warnings. Also, I tried to search for something on Google, but couldn't find situations similar to mine. What could be the cause of such strange behaviour?

PS: The implementation of the copy constructor:

document::document (const document& a) :
    denumire(new char [strlen(a.denumire)+1]),
    tema(new char[strlen(a.tema)+1]),
    autorul(new char[strlen(a.autorul)+1]),
    num_pag(a.num_pag),
    last_edit(a.last_edit)
{
    strcpy(denumire,a.denumire);
    strcpy(tema,a.tema);
    strcpy(autorul,a.autorul);
}

I took it from a teacher's examples. Also, I initialise the variables in the following way:

document c(s1.c_str(),s2.c_str(),s3.c_str(),i1,d1)

because the teacher requires us that the object contains dinamically created strings :)


Note sure about what exactly is the problem but can give you some pointers. A segmentation fault occurs due to the following reasons: 1) You try to access a memory area that is not in the address space of the process 2) You try to use an uninitialized pointer

By address space, I mean the memory allocated to the process in the RAM

Hope it helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜