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() gives 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.
I'd like to be really sure that the reservation of memory for the result
variable has been performed successfully. 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.
The programming environment is based on Windows kits, version 8.1.
CByteArray
is MFC code.
I don't know if this is relevant, but the CByteArray
contains quite some backslash characters.
Unlike other MFC classes, CByteArray
does not come with a static buffer in front of all other class members, nor a dereferencing operator. Thus the wrapped byte array can't be accessed by dereferencing the CByteArray
variable. (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. 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:
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.