Reputation: 3462
I am new in c++ area.
On line memcpy(combined + 14 + 40, pThirdPart, size);
it's throws
Exception thrown at 0x0FB046EE (vcruntime140d.dll) in Memcpy.exe: 0xC0000005: Access violation reading location 0x00544000.
Why it's happening?
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);
Upvotes: 0
Views: 1557
Reputation: 1135
pThirdPart
points to the address of thirdPart
, not the address pointed to by *thirdPart
.
You are probably confused because the address of an array is not the same as the address of a pointer. When you have an array like so
char array[10];
taking the address of this variable is the same as just referencing it without and index. array
is the same value as &array
.
But with a pointer the situation is different
char *pointer;
pointer
is not the same value as &pointer
This is just a quirk of C/C++ that you have to be aware of.
So in your program you should have
BYTE *pFirstPart = reinterpret_cast<BYTE*>(&firstPart);
BYTE *pSecondPart = reinterpret_cast<BYTE*>(&secondPart);
BYTE *pThirdPart = reinterpret_cast<BYTE*>(thirdPart);
or even
BYTE *pFirstPart = reinterpret_cast<BYTE*>(firstPart);
BYTE *pSecondPart = reinterpret_cast<BYTE*>(secondPart);
BYTE *pThirdPart = reinterpret_cast<BYTE*>(thirdPart);
both variants will work.
Upvotes: 2