#include #include using namespace std;

class Student { private: char *m_name; int m_ID; int m_age;

public: Student(const char *name, int ID , int age); ~Student(); };

Student::Student(const char *name, int ID, int age) : m_ID(ID), m_age(age) { strcpy(m_name, name); cout << FUNCTION << endl; }

Student::~Student() { cout << FUNCTION << endl; }

void test(char *name, int ID, int age) { Student *p = new Student(name,ID,age);

delete p;

}

int main() { char *name = "zhangsan"; test(name, 1000238, 22);

return 0;

}

以上代码出现段错误,如何解决?

在类的构造函数中,使用了strcpy函数将name拷贝到了m_name指向的内存空间,但是在构造函数中并没有为m_name分配内存空间,导致拷贝时发生段错误。

解决方法是在构造函数中为m_name动态分配内存空间,然后再进行拷贝操作。

修改后的代码如下:

#include <iostream>
#include <cstring>
using namespace std;

class Student
{
private:
    char *m_name;
    int m_ID;
    int m_age;

public:
    Student(const char *name, int ID , int age);
    ~Student();
};

Student::Student(const char *name, int ID, int age) : m_ID(ID), m_age(age)
{
    m_name = new char[strlen(name) + 1];
    strcpy(m_name, name);
    cout << __FUNCTION__ << endl;
}

Student::~Student()
{
    delete[] m_name;
    cout << __FUNCTION__ << endl;
}

void test(const char *name, int ID, int age)
{
    Student *p = new Student(name,ID,age);

    delete p;
}

int main()
{
    const char *name = "zhangsan";
    test(name, 1000238, 22);

    return 0;
}

在修改后的代码中,我们在构造函数中使用new char[strlen(name) + 1]为m_name动态分配了内存空间,并且在析构函数中使用delete[] m_name释放了这块内存空间。这样就避免了段错误的发生。

C++ 段错误解决:Student 类构造函数中的内存分配

原文地址: https://www.cveoy.top/t/topic/lNhG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录