【问题标题】:How to deal with access writing violation error? [duplicate]如何处理访问写入冲突错误? [复制]
【发布时间】:2021-10-13 17:10:42
【问题描述】:

我创建了一个小程序来试验链表。然而,当我运行它时,我在 jerry->age = 45 处得到一个“访问冲突写入位置”。我不确定我做错了什么。

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

struct Person {
    string name;
    int age;
    char gender; 
    struct Person* contact;
};

int main() {
    struct Person* jerry = (struct Person*) malloc(sizeof(struct Person));
    jerry->name = "Jerry";
    jerry->age = 45;
    jerry->gender = 'M';
    jerry->contact = (struct Person*)malloc(sizeof(struct Person));;
    printf("Hi! My name is %s.\n I am %d years old.\n I am ");
    printf((jerry->gender == 'M') ? " a man.\n" : " a woman.\n", jerry->gender);
    printf("I happen to know ");
}

编辑:

我的新代码如下:

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

class Person {
public:
    Person(const string& name, int age, char gender, const Person* contact) : _name(name), _age(age), _gender(gender), _contact(contact) {}
    
public:
    string getName() {
        return _name;
    }
    int getAge() {
        return _age;
    }
    char getGender() {
        return _gender;
    }

private:
    string _name;
    int _age;
    char _gender;
    const Person* _contact;
    /*Person* getPerson() {
        return _contact;
    }*/
};

int main() {
    Person jerry("Jerry", 45, 'M', nullptr);
    Person simon("simon", 58, 'M', nullptr);

    printf("Hi! My name is %s.\n I am %d years old.\n I am", jerry.getName(), jerry.getAge());
    printf((jerry.getGender() == 'M') ? " a man.\n" : " a woman.\n", jerry.getGender());
    printf("I happen to know ");
}

如何访问 Person 类中的指针联系人?

【问题讨论】:

  • 哪个操作系统和平台?
  • 如果是 c++ 为什么要使用 malloc ?
  • 无法用 gcc 重现。至于你没有描述的问题,他第一个printf()调用有未定义的行为,因为它包含两个格式说明符,但没有对应的参数。
  • 我的猜测是 malloc 由于结构内的字符串而失败。最有可能的是,字符串在后台使用new,而混合mallocnew 是不好的。它在我的机器/在线编译器上崩溃。

标签: c++


【解决方案1】:

当您使用malloc 分配您的struct 时,您不会为std::string 运行ctor。

您应该为您的 struct 创建一个 ctor,在其中正确初始化字符串,并使用 ctor 而不是 malloc 创建对象(在创建指针时使用 newdelete)。

定义类的代码示例:

class Person {
public:
    Person(const string& name, int age, char gender, const Person* contact) : _name(name), _age(age), _gender(gender), _contact(contact) {}

private:
    string _name;
    int _age;
    char _gender;
    const Person* _contact;
};

使用该类的代码示例:

Person jerry("Jerry", 45, 'M', nullptr);
Person jerry2("Jerry2", 45, 'M', &jerry);

Person* jerry3 = new Person("Jerry3", 45, 'M', &jerry);
delete jerry3;

contact 的指针用法可能不安全,应该更改。

【讨论】:

  • 创建一个 ctor 没有帮助,它已经有一个合适的默认 ctor。问题是 malloc 不调用ctor。
  • 正确,这还不够,您需要使用ctor而不是malloc创建对象,并在答案中添加。
  • 你能举一个这段代码的例子吗?
  • @Programmer - 添加示例
猜你喜欢
  • 1970-01-01
  • 2019-12-31
  • 1970-01-01
  • 1970-01-01
  • 2015-06-19
  • 1970-01-01
  • 2012-11-01
  • 1970-01-01
相关资源
最近更新 更多