为 Mbed BufferedSerial 对象分配的动态内存大小错误
Wrong dynamic memory size allocated for Mbed BufferedSerial object
我正在尝试在 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.
…
}
David Schwartz 的评论给了我寻找不匹配的 pre-processor MACRO 定义的线索。
问题出在 DEVICE_SERIAL_FC pre-processor 宏上。当 mbed 被构建为一个库时,宏被启用。但是,当在项目中使用该库及其头文件时,它被禁用了。这种不匹配导致了问题。
我正在尝试在 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.
…
}
David Schwartz 的评论给了我寻找不匹配的 pre-processor MACRO 定义的线索。 问题出在 DEVICE_SERIAL_FC pre-processor 宏上。当 mbed 被构建为一个库时,宏被启用。但是,当在项目中使用该库及其头文件时,它被禁用了。这种不匹配导致了问题。