Reintepret强制转换和指针删除 [英] Reintepret cast and Pointer deletion

查看:79
本文介绍了Reintepret强制转换和指针删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I find the following error in my recent implementation.

#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
 
}

这是删除指针的错误方法吗?

Is this is a wrong way to delete the pointer?

谢谢

推荐答案

这听起来有点像OP试图准备由标头和 float 序列组成的二进制数据.为此(并克服 M.Salters 中提到的对齐问题),我将使用 std :: vector< char> ,将其调整为相应的大小.完整尺寸的预期二进制输出,然后将其中的内容(标头和浮点值) std :: memcpy()放入其中.

This somehow sounds like OP tries to prepare binary data consisting of a header and a sequence of floats. To achieve this (and overcome the alignment issues mentioned by M.Salters), I would use a std::vector<char>, resize it to the resp. full size of expected binary output, and then std::memcpy() the contents (header and the float values) into it.

我的 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

在大肠杆菌上进行实时演示

注意:

代码中唯一剩下的重新解释广播位于:

The only reinterpret-cast left in the code is in:

  std::memcpy(&buffer[sizeHeader], (const char*)payload, sizeData);

可能对于OP这样的用例,对于 char (以及类似的类型,例如 unsigned char )有一些特定的例外,涉及重新解释广播

Probably for exactly such use-cases like the one of OP, there are specific exceptions made for char (and comparable types like unsigned char) concerning the reinterpret-casting.

来自 cppreference.com:重新解释转换 :

AliasedType为 std :: byte (自C ++ 17起), char unsigned char :这允许检查对象将任何对象表示为字节数组.

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.

这篇关于Reintepret强制转换和指针删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆