aaaa
aaaa

Reputation: 67

VirtualAlloc problem allocating memory for bulk file reading

Im trying to read some data from a binary file into a buffer allocated with VirtualAlloc. The problem is that i get a "bad Pr" problem and can't perform an fread. Here is my code:

fseek(myfile,0, SEEK_END);
DWORD FileSize = ftell(myfile);
fseek(myfile,0, SEEK_SET);
BYTE *buf = (BYTE * )VirtualAlloc(NULL,FileSize,MEM_RESERVE, PAGE_EXECUTE_READWRITE);
fread(buf,sizeof(BYTE),1,myfile);

the fread - fails. what am i doing wrong?

Thanks!

Upvotes: 2

Views: 648

Answers (1)

Erik
Erik

Reputation: 91270

You need to pass both MEM_RESERVE and MEM_COMMIT. And you need to use a BYTE *, not a BYTE

fseek(myfile,0, SEEK_END);    
DWORD FileSize = ftell(myfile);    
fseek(myfile,0, SEEK_SET);    
BYTE * buf = (BYTE*)VirtualAlloc(NULL,FileSize,MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
fread(buf,FileSize,1,myfile);

Upvotes: 3

Related Questions