【发布时间】:2020-05-18 10:22:02
【问题描述】:
下面的程序可以运行,直到缓冲区大小达到 135。 如果缓冲区变大,前 3.5 个字节将打印为 0。 (在 MKR1000 arduino 上)
uint8_t* bufferOut;
size_t sizeOut;
void SendMessage()
{
fillBuffer();
sendBuffer();
}
void fillBuffer()
{
sizeOut = 12; //just an example
uint8_t* tempBuffer2 = new uint8_t[sizeOut];
bufferOut = tempBuffer2;
delete[] tempBuffer2;
}
void sendBuffer()
{
Serial.Write(bufferOut, sizeOut);
}
我做错了什么? std::vector 会更适合这里吗?
谢谢!
【问题讨论】:
-
delete[] tempBuffer2;- 你认为留下bufferOut指向什么?您刚刚删除了之前分配两行的指针后面的内存,并在前一行存储在bufferOut中,使其悬空。任何进一步取消引用调用未定义的行为。是的,std::vector几乎总是更适合手动内存管理。 -
我们需要实际的、完整的代码。就目前而言,代码没有意义。您不使用分配和释放之间的内存,那么为什么要首先分配它呢?还有,第一个函数和第二个函数有什么关系?
-
delete original array pointer after copy set the first 3 bytes to 0 — 没有合法的方法可以找到它。
标签: c++ arrays pointers arduino delete-operator