0

我正在从光盘读取原始字节并尝试以十六进制打印它们。我在 ConsoleApp.exe 中收到“0x666CDF46 (msvcr110d.dll) 处的未处理异常:0xC0000005:访问冲突写入位置 0x002EC000。” 在 for 循环内。我的猜测是我跑完了 TCHAR 数组的末尾,str但我不知道为什么。dwBytesRead并且dwSize是 4096。for 循环在 4027 时停止异常i,我相信它应该到达 4096。有人可以对此有所了解吗?

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);
            ...
        }

        ...
    }
}
4

1 回答 1

3

dwBytesRead在调用内部的使用_stprintf_s无效。您正在告诉_stprintf_s目标缓冲区的大小,对于循环中的每次迭代,都从特定点开始str并扩展到dwBytesRead字符。这是不正确的,尤其是当您的循环迭代器i到达缓冲区的末尾时。

您可以通过以下方式解决此问题:

            _stprintf_s(str+2*i, (size*2+1) - (2*i), L"%02x", lpSector[i]);

我很难说这是否真的能解决你的问题,因为目前还不清楚问题的根源究竟是什么。

于 2012-12-26T00:36:20.963 回答