我在最近的实现中发现以下错误。
#include<iostream>
using namespace std;
void main()
{
string header="apple"
float* p = new float[10];
double*Data = NULL;
p = reinterpret_cast<float*>(reinterpret_cast<char*>(p) + header.length());
//fetch data from an another call// - it doesn't matter here as how it is returned.
for(int i=0;i<10;i++)
{
p[i] = static_cast<float>(Data[i]);
}
//publish the output to the debug window //
delete[] p; // throws _block_type_is_valid(pHead->nblockuse) crash
}
这是删除指针的错误方法吗?谢谢
最佳答案
这听起来有点像OP试图准备由 header 和float
序列组成的二进制数据。为了实现这一点(并克服M.Salters提到的对齐问题),我将使用std::vector<char>
,将其调整为相应的大小。完整的预期二进制输出,然后将内容( header 和浮点值)std::memcpy()
到其中。
我的MCVE演示了这一点:
#include <cstring>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
int main()
{
const std::string header = "FloatData";
const float payload[] = { 1.0f, 2.0f, 3.0f };
// determine binary size of header and payload
const size_t sizeHeader = header.size();
const size_t sizeData = sizeof payload;
const size_t sizeTotal = sizeHeader + sizeData;
// prepare binary buffer
std::vector<char> buffer(sizeTotal);
std::memcpy(&buffer[0], header.data(), sizeHeader);
std::memcpy(&buffer[sizeHeader], (const char*)payload, sizeData);
// dump binary buffer
std::cout << "Buffer: " << buffer.size() << " Bytes, Dump:\n";
for (unsigned char byte : buffer) {
std::cout << ' ' << std::hex << std::setw(2) << std::setfill('0') << (unsigned)byte;
}
std::cout << '\n';
}
输出:Buffer: 21 Bytes, Dump:
46 6c 6f 61 74 44 61 74 61 00 00 80 3f 00 00 00 40 00 00 40 40
Live Demo on coliru注意:
代码中剩下的唯一重新解释广播位于:
std::memcpy(&buffer[sizeHeader], (const char*)payload, sizeData);
可能恰好像OP之一这样的用例,对于char
(以及类似的类型,例如unsigned char
),存在有关重新解释广播的特定异常(exception)。从cppreference.com: reinterpret_cast conversion:
AliasedType is
std::byte
(since C++17),char
, orunsigned char
: this permits examination of the object representation of any object as an array of bytes.
关于c++ - Reinterpret_cast和指针删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64153387/