简体   繁体   English

将 CByteArray 复制到 Bytes 数组中会导致访问冲突

[英]Copying a CByteArray into an array of Bytes causes an access violation

While investigating a dump, I'm dealing with an access violation, caused by this piece of source code:在调查转储时,我正在处理由这段源代码引起的访问冲突:

CByteArray baInput;
... // baInput gets filled in with 9804 entries
BYTE* result;
result = new BYTE[baInput.GetSize()]; // baInput.GetSize() yields 9804, as expected.
memcpy (result, &baInput, baInput.GetSize()); // access violation

In order to understand what's going on, I've added sizeof(result) in the watch-window, which yields 8 (while I expected 9804), but I'm not sure if this is the right thing to do here.为了了解发生了什么,我在监视窗口中添加了sizeof(result) ,结果为8 (而我预计为 9804),但我不确定这是否是正确的做法。

I'd like to be really sure that the reservation of memory for the result variable has been performed successfully.我想确定result变量的内存保留是否已成功执行。 How can I do that?我怎样才能做到这一点?

Does anybody have an idea what might be going wrong here?有人知道这里可能出了什么问题吗?
Thanks in advance提前致谢

Oh, I forgot: I'm working on a Windows environment, most probably Windows-10.哦,我忘了:我正在使用 Windows 环境,很可能是 Windows-10。
The programming environment is based on Windows kits, version 8.1.编程环境基于 Windows 工具包,版本 8.1。
CByteArray is MFC code.CByteArray是 MFC 代码。

I don't know if this is relevant, but the CByteArray contains quite some backslash characters.我不知道这是否相关,但CByteArray包含相当多的反斜杠字符。

Unlike other MFC classes, CByteArray does not come with a static buffer in front of all other class members, nor a dereferencing operator.与其他 MFC 类不同, CByteArray在所有其他类成员之前没有附带静态缓冲区,也没有取消引用运算符。 Thus the wrapped byte array can't be accessed by dereferencing the CByteArray variable.因此,无法通过取消引用CByteArray变量来访问包装的字节数组。 (Doing that will give you a pointer to the memory location of the wrapper class, as others mentioned) (这样做会给你一个指向包装类的内存位置的指针,正如其他人提到的)

It does however inherit and override GetData() from CObArray which grants readonly access to the wrapped array.但是,它确实从CObArray继承并覆盖GetData() ,从而授予对包装数组的只读访问权限。 With this you can adjust your code to the following:有了这个,您可以将您的代码调整为以下内容:

CByteArray baInput;
...
BYTE* copy = new BYTE[baInput.GetSize()];
memcpy(copy, baInput.GetData(), baInput.GetSize());

Using C++ however, the better approach would be using a vector for the data:然而,使用 C++,更好的方法是使用数据向量:

CByteArray baInput;
...
std::vector<BYTE> copy(baInput.GetData(), baInput.GetData() + baInput.GetSize());

Note that there are several ways to assign the data to the vector.请注意,有几种方法可以将数据分配给向量。 This one treats the source pointers as iterators and is one of the quickest.这个将源指针视为迭代器,是最快的之一。 You can also access the vector's data using std::vector::data() later on again.您还可以稍后再次使用std::vector::data()访问向量的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM