【问题标题】:Copying an array from a struct which is senе through a function从通过函数感知的结构复制数组
【发布时间】:2016-10-19 13:39:11
【问题描述】:

我想向 json->setInformation 发送一个结构,但是当我尝试复制结构内的数组时,我的程序崩溃了。其余数据都还好,只是导致崩溃发生的数组。

info = data->getInformation();

json->setInformation(info);

getInformation 返回一个我可以在main.cpp 中读取的结构 当我尝试将此结构发送到 setInformation 时,它崩溃了......

information.h 包含我的结构

struct information{
        String location;
        String protocol;
        uint8_t groupID;
        uint8_t* data;

information& operator=(const struct information& that){
    location = that.location;
    protocol = that.protocol;
    groupID = that.groupID;
    for (int i = 0; i < 9; ++i){
        data[i] = that.data[i];
    }
    return *this;
}
};

json.cpp

void JSON::setInformation(information data){
info->location = data.location;
info->protocol = data.protocol;
info->groupID = data.groupID;
// for (int i = 0; i < 9; ++i){
//     info->data[i] = data.data[i];
// }
// Serial.print("after JSON: ");
// Serial.println(info->data[0]);
}

这段代码工作正常,但是当我取消注释应该复制数组的 for lop 时,它会崩溃

【问题讨论】:

  • 你的结构没有数组。它有一个指针。想想指针指向什么。
  • 您究竟在哪里设置data 字段以指向适当大小的有效内存块?
  • 考虑发布更多代码(特别是关于 uint8_t 数组分配/释放)。
  • 顺便说一句,阅读您的代码,看起来您不妨声明uint8_t data[9],并在operator= 函数中,只需执行return *this = that(顺便说一句,这意味着您不甚至需要这个函数,因为语言标准已经支持结构赋值)。

标签: c++ arrays function struct


【解决方案1】:

您在使用之前是否为 uint8_t data* 参数分配了内存?

然后记得在不再需要的时候释放内存,从而避免内存泄漏。

【讨论】:

  • 我用 calloc 分配了 uint8_t 数据,现在可以正常使用了,非常感谢
【解决方案2】:

您的对象通过副本传递给函数,但您没有复制构造函数。

默认复制构造函数不会正确复制原始指针。因此,要么声明并实现复制构造函数,要么将原始指针 (uint8_t*) 替换为可安全复制的 vector (std::vector&lt;uint8_t&gt;)(然后复制对象将成为有效操作)。

此外,我们看不到谁在分配/释放您的原始指针,但我怀疑您也缺少析构函数。

您的代码破坏了rule of three,这是您将在 C++ 中声明的任何类的最低要求。

【讨论】:

  • 在你的回答中提到the rule of 3
  • 代码中没有任何内容表明缺少复制构造函数可能是问题所在。
  • 甚至rule of 5
  • 指针将被完美复制,唯一可能发生的问题是它是否被释放 - 我们看不到这一点。
  • @juanchopanza:是的,但也没有分配原始指针,我怀疑不是所有代码都已发布。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-22
  • 1970-01-01
  • 1970-01-01
  • 2011-05-06
  • 2013-03-05
  • 2012-07-03
相关资源
最近更新 更多