【问题标题】:Memory allocation problem when creating a class C++创建类 C++ 时的内存分配问题
【发布时间】:2011-08-22 09:55:29
【问题描述】:

仍在学习 C++,但仍有特定错误:)。我有以下组成的对象:

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);
};

问题是当我尝试使用以下构造函数对其进行初始化时,出现分段错误:

document::document (char *s1, char *s2, char *s3, int i1, data d1) {
    denumire=new char[strlen(s1)+1];
    strcpy(denumire,s1);
    tema=new char[strlen(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";
}

据我了解,所有变量均已正确分配,因为出现“Setarea documentului finisata”消息,然后出现段错误。所有代码都可以正常编译,没有任何警告。 另外,我试图在谷歌上搜索一些东西,但找不到与我类似的情况。这种奇怪行为的原因可能是什么?

PS:复制构造函数的实现:

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);
}

我从老师的例子中得到它。另外,我通过以下方式初始化变量:

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

因为老师要求我们对象包含动态创建的字符串:)

【问题讨论】:

  • 不要使用 new char[] ,使用 std::string。
  • 那么问题不在于该代码,如果它到达它的末尾。将调试器插入其中,看看它到底在哪里崩溃。很可能您正在其他地方覆盖一些内存,这会导致内存分配终止。
  • 一般说明:由于这是C++,所以使用std::string来表示字符串,而不是char *。此外,在构造函数的初始化列表中初始化您的成员,而不是在正文中。
  • unapersson,Space_C0wb0y,我也不喜欢使用 C 类型字符串的想法,但是我必须向其提供这段代码的老师需要使用手动分配的字符串 :( 我尝试在 main() 中使用 C++ 风格的字符串,但是在将它们传输到函数时,我将它们转换为 const char*,然后将 strcpy 转换为对象:)
  • @Ion 找一个新老师 - 任何让你使用 char * 的人都不适合教任何有关 C++ 的内容。

标签: c++ class memory-management dynamic-allocation


【解决方案1】:

注意确定到底是什么问题,但可以给你一些指示。出现分段错误的原因如下: 1)您尝试访问不在进程地址空间中的内存区域 2)您尝试使用未初始化的指针

地址空间是指RAM中分配给进程的内存

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 2019-12-18
    • 2016-06-19
    • 2016-09-14
    相关资源
    最近更新 更多