c++ - Reinterpret_cast和指针删除

标签 c++ pointers exception

我在最近的实现中发现以下错误。

#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, or unsigned 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/

相关文章:

c++ - 在 VS2012 C++ 中使用 ZeroMQ

c++ - 使用构造函数初始化您的类,该构造函数将 std::map 作为带有大括号括起来的初始化程序的参数

检查宏参数是否为指针

c# - 正确处理两个 WebException

c++ - 为什么 gcc 在按值传递微不足道的结构时会发出不需要的内存访问?

C++ kbhit 与 if 语句滞后

c - 在没有 '&' 的情况下分配时发出警告的数组指针的地址

c - 确保只将指针传递给可变参数函数

scala - Apache Spark : dealing with Option/Some/None in RDDs

java - 抛出 java 异常并停止