【发布时间】:2020-11-23 11:52:44
【问题描述】:
我正在尝试在 nrf52840 的堆中分配 mbed::BufferedSerial 对象的两个实例。第一次分配成功,第一个串口实例工作正常,但是,在创建第二个串口对象实例后,第一个实例停止工作。调试显示第二个对象覆盖了内存中第一个对象的最后 16 个字节。原因是虽然 sizeof(BufferedSerial object) 是 856 字节,但 new 运算符只分配了 840 字节,因此在下一次堆分配时会覆盖最后 16 字节。
传递的count参数是840B:operator new (std::size_t count)
对象创建后大小为856B:sizeof(*g_serial_port[0])
有谁知道为什么会发生这种情况以及如何解决它?做分配的那段代码就是这样(用 GNU Tools Arm Embedded 9 2019-q4-major 编译的):
serial_api.cpp
static mbed::BufferedSerial *g_serial_port[2] =
{ NULL };
extern “C” void create(id, tx , rx)
{
g_serial_port[id] = new mbed::BufferedSerial(tx, rx);
}
main.c
int main()
{
create(0, P1_14, P1_15); //the heap allocated is 16 bytes smaller than the object
create(1, P1_12, P1_13); // this object's allocation overwrites the last 16 bytes of the previous one.
…
}
【问题讨论】:
-
我敢打赌,编译器选项或头文件包含的某些更改会导致
sizeof (mbed::BufferedSerial)在两个不同的地方有所不同。一个ifdef或包含两个不同的头文件,它们提供相同类型名称的不同定义将执行此操作。编译器选项也一样,这些选项会更改int或double等标准类型的大小。在main中记录或输出该值,我敢打赌你会得到一个更小的值。
标签: c++ arm heap-memory new-operator mbed