【问题标题】:C++ memcpy Access violation big chunk of memoryC++ memcpy 访问冲突大块内存
【发布时间】:2018-07-23 16:23:06
【问题描述】:

我是 C++ 领域的新手。 在线memcpy(combined + 14 + 40, pThirdPart, size); 抛出

在 Memcpy.exe 的 0x0FB046EE (vcruntime140d.dll) 处引发异常: 0xC0000005:访问冲突读取位置0x00544000。

为什么会这样?

const long size = 8294400;
char firstPart[14] = "3412345";
char secondPart[40] = "daffda";
char *thirdPart = new char[size];

sprintf_s(thirdPart, size, "Test TEst tset ... and other symbols");

BYTE *pFirstPart = reinterpret_cast<BYTE*>(&firstPart);
BYTE *pSecondPart = reinterpret_cast<BYTE*>(&secondPart);
BYTE *pThirdPart = reinterpret_cast<BYTE*>(&thirdPart);

BYTE *combined = new BYTE[(size + 14 + 40)];

memcpy(combined, pFirstPart, 14);
memcpy(combined + 14, pSecondPart, 40);
memcpy(combined + 14 + 40, pThirdPart, size);

【问题讨论】:

  • 必问问题:你为什么不直接使用std::string?
  • 什么是BYTE?
  • 我猜想reinterpret_cast&lt;BYTE*&gt;(&amp;thirdPart); 应该是reinterpret_cast&lt;BYTE*&gt;(thirdPart); - 虽然我真的不确定所有这些reinterpret_casts 的意义是什么
  • @nvoigt Windows Data Types: typedef unsigned char BYTE;
  • std::byte 是一个东西。

标签: c++


【解决方案1】:

pThirdPart指向thirdPart的地址,而不是*thirdPart指向的地址。

您可能会感到困惑,因为数组的地址与指针的地址不同。当你有一个这样的数组时

char array[10];

获取该变量的地址与仅引用它没有和索引相同。 array 与 &amp;array 的值相同。

但是有了指针情况就不同了

char *pointer;

pointer 与&amp;pointer 的值不同

这只是你必须注意的 C/C++ 的一个怪癖。

所以在你的程序中你应该有

BYTE *pFirstPart = reinterpret_cast<BYTE*>(&firstPart);
BYTE *pSecondPart = reinterpret_cast<BYTE*>(&secondPart);
BYTE *pThirdPart = reinterpret_cast<BYTE*>(thirdPart);

甚至

BYTE *pFirstPart = reinterpret_cast<BYTE*>(firstPart);
BYTE *pSecondPart = reinterpret_cast<BYTE*>(secondPart);
BYTE *pThirdPart = reinterpret_cast<BYTE*>(thirdPart);

两种变体都可以。

【讨论】:

    猜你喜欢
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2015-01-26
    • 1970-01-01
    相关资源
    最近更新 更多