Writefile导致崩溃,访问冲突

时间:2013-06-16 05:39:54

标签: c++ file-io access-violation

所以基本上我希望将一个字节数组写入文件,但程序崩溃了。 append.exe中0x7766DEE1(KernelBase.dll)的未处理异常:0xC0000005:访问冲突写入位置0x00000000。

BYTE *image ;
BYTE *bigMem;
#define REASONABLY_LARGE_BUFFER 16777216
file = CreateFile(fileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

fileSize = GetFileSize(file, NULL);

bigMem = (BYTE *)HeapCreate(NULL, REASONABLY_LARGE_BUFFER, 0);
image = (BYTE *)HeapAlloc(bigMem, HEAP_ZERO_MEMORY, fileSize);
if (bigMem == NULL || image == NULL){
    printf("Allocation failed");
    return EXIT_FAILURE;
}
printf("We are writing to the file %p, with data location %p, and filesize %d\n", file, image, fileSize);
LPDWORD at = 0;
WriteFile(file, image, fileSize, at, NULL);

该印刷品说: 我们正在写入文件00000038,数据位置为02451590,文件大小为161169

1 个答案:

答案 0 :(得分:17)

如果重叠结构的参数不是,则传递给WriteFile的参数用于存储写入的字节数(at为空 null。我建议将at更改为DWORD并传递指针。

DWORD at;
WriteFile(file, image, fileSize, &at, NULL);