Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writefile causes crash, with access violation

So basically I wish to write a byte array to a file, however the program crashes. Unhandled exception at 0x7766DEE1 (KernelBase.dll) in append.exe: 0xC0000005: Access violation writing location 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);

That print says: We are writing to the file 00000038, with data location 02451590, and filesize 161169

like image 394
ThePlague Avatar asked Jun 16 '13 05:06

ThePlague


1 Answers

The argument passed to WriteFile used to store the number of bytes written (at) can only be null if the argument for the overlapped structure is not null. I suggest changing at to be a DWORD and pass a pointer to it.

DWORD at;
WriteFile(file, image, fileSize, &at, NULL);
like image 52
Captain Obvlious Avatar answered Nov 06 '22 13:11

Captain Obvlious