I’m reading raw bytes from a disc and trying to print them in Hex. I’m getting an “Unhandled exception at 0x666CDF46 (msvcr110d.dll) in ConsoleApp.exe: 0xC0000005: Access violation writing location 0x002EC000.” inside the for loop. My guess is I’m running off the end of the TCHAR array str but I can’t figure out why. dwBytesRead and dwSize are 4096. The for loop stops for the exception when i is 4027 and I believe it should get to 4096. Can someone shed some light on this?
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hCD, hFile;
DWORD dwBytesRead;
hFile = CreateFile (L"sector.dat",...);
hCD = CreateFile (L"\\\\.\\E:", ...);
if (hCD != INVALID_HANDLE_VALUE)
{
DISK_GEOMETRY dgCDROM;
...
LPBYTE lpSector;
DWORD dwSize = 2 * dgCDROM.BytesPerSector; // 2 sectors
lpSector = (LPBYTE) VirtualAlloc (NULL, dwSize,
MEM_COMMIT|MEM_RESERVE,
PAGE_READWRITE);
....
if (ReadFile (hCD, lpSector, dwSize, &dwBytesRead, NULL)) {
const int size = (int) dwBytesRead;
TCHAR *str = new TCHAR[size*2+1];
int i;
for (i=0; i<size;i++) {
_stprintf_s(str+2*i, (size_t) dwBytesRead, L"%02x", lpSector[i]);
}
str[2*i]=L'\0';
OutputDebugString(str);
...
}
...
}
}
Your use of
dwBytesReadinside the call to_stprintf_sis not valid. You are telling_stprintf_sthat the size of the destination buffer, for every iteration through the loop, starts at a particular point instrand extends fordwBytesReadcharacters. This is not true, especially as your loop iteratorireaches the end of the buffer.You can fix this with something like:
It’s hard for me to say whether this will actually fix your problem, because it’s unclear what the root of the problem really is.