Reputation: 2409
static void InvShiftRows(BYTE* dest)
{
tcout << "\t\t\tInvShiftRows()+" << EOL;
BYTE* temp = new BYTE[16];
ByteUtil::LogArray("temp1", temp, 16);
memcpy(temp, dest, 16);
ByteUtil::LogArray("temp2", temp, 16);
dest[0x01] = temp[0x0D];
dest[0x02] = temp[0x0A];
dest[0x03] = temp[0x07];
dest[0x05] = temp[0x01];
dest[0x06] = temp[0x0E];
dest[0x07] = temp[0x0B];
dest[0x09] = temp[0x05];
dest[0x0A] = temp[0x02];
dest[0x0B] = temp[0x0F];
dest[0x0D] = temp[0x09];
dest[0x0E] = temp[0x06];
dest[0x0F] = temp[0x03];
ByteUtil::LogArray("Dest1", dest, 16);
delete[] temp;
tcout << "\t\t\tInvShiftRows()-" << EOL;
}
So i've traced down that the access violation happens occasionally on the delete[] temp
and for the life of me i can not figure out why. It only does it randomly. Any clue as to why?
EDIT per request to see ByteUtil::LogArray
void ByteUtil::LogArray(char* header, const BYTE* thearray, int length)
{
tcout << header << "(" << length << ")-";
char* number = new char[4];
for(int i=0; i<length; i++)
{
sprintf_s(number, 4,"%02X:", thearray[i]);
wcout << number;
}
delete[] number;
wcout << EOL; //EOL is just std::endl << std::flush
}
honestly i think I made a few bad moves with delete[]. I learned in one of my code review posts that I should use delete[] whenever I use new X[] so I started putting them everywhere that I had something like BYTE temp[4]
i would replace with BYTE* temp = new BYTE[4]
and add a corresponding delete[]. and at first it appeared that if i used new X[] that it would set all the values in that array to zero (turned out to be bogus, as it was throwing off my encrypt/decrypt methods) So now I'm trying to figure out which one of my deletes is deleting too much... which makes me want to ask another question..
is it irresponsible to have BYTE temp[4] = {0x00};
in a method? or is it better practice to use new X[]
and delete[]
?
Upvotes: 0
Views: 95
Reputation: 3112
If the problem is related to the heap corruption, you can include <crtdbg.h>
and turn ON heap checks for every alloc/dealloc:
Run somewhere at the beginning of the app:
// _CRTDBG_ALLOC_MEM_DF -- Turn on debug allocation
// _CRTDBG_CHECK_ALWAYS_DF -- check the heap's integrity at every allocation and deallocation.
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF);
If the problem is heap-related, you'll get an assertion (Debug Assertion Failed! Expression: _CrtCheckMemory()). After this point trace back the program execution and look for the place where the heap is corrupted.
E.g. if you add dest[0x10] = temp[0x03];
to your code above and dest was allocated on the heap, you'll get an assertion inside LogArray on cout.
NOTE: setting _CRTDBG_CHECK_ALWAYS_DF could make your app run slow.
Upvotes: 1