-3

Can anyone help me as what is going wrong here? Am not able to allocate memory using malloc...

    bReadFile = ReadFile( hConsoleFile, &ReadFileBuffer, MaxCharToRead, &CharsRead, NULL );
Abhineet
  • 5,320
  • 1
  • 25
  • 43
  • 3
    How big is the file? How much memory do you have? – Mysticial Feb 04 '12 at 06:15
  • 1
    What happens when you try to run that code? – ObscureRobot Feb 04 '12 at 06:16
  • We need more details-- are you getting a compile-time error (an error when you run the compiler) or a run-time error (an error when you run the program?) What is the text of the error message? – Max E. Feb 04 '12 at 06:17
  • 1
    I get a in my ReadFileBuffer...the file is just 35 chars which dwFileSize reads perfectly. – Abhineet Feb 04 '12 at 06:18
  • malloc usually fails because it cant allocate enough memory. Set a breakpoint or print the value of dwFileSize and make sure you have enough Memory to allocate it. Try allocating a static amount and reading the file in chunks if the file is large. – Brad Feb 04 '12 at 06:20
  • Actually it does not throws any error and successfully goes to the next method. But the ReadFileBuffer fails to read anything inside the File. Then I debugged it and saw the problem with ReadFileBuffer as . Is this the correct way to assign malloc for BYTE data types? – Abhineet Feb 04 '12 at 06:22
  • I have set a breakpoint and saw the dwFileSize in debug mode that it reads perfectly the size of File. – Abhineet Feb 04 '12 at 06:25

2 Answers2

3

You have &ReadFileBuffer in the call to ReadFile. You are supposed to pass ReadFile a pointer to the buffer, not a pointer to a pointer to the buffer.

From the documentation:

lpBuffer [out]
    A pointer to the buffer that receives the data read from a file or device.

Since ReadFileBuffer is a pointer to the buffer, that's what you should be passing.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
1

The signature for ReadFile() is this:

BOOL WINAPI ReadFile(
  __in         HANDLE hFile,
  __out        LPVOID lpBuffer,
  __in         DWORD nNumberOfBytesToRead,
  __out_opt    LPDWORD lpNumberOfBytesRead,
  __inout_opt  LPOVERLAPPED lpOverlapped
);

The second parameter should be a pointer to your buffer, not a pointer to a pointer to your buffer. That's what you got when you did &ReadFileBuffer. The call should be:

bReadFile = ReadFile(hConsoleFile, ReadFileBuffer, MaxCharToRead, &CharsRead, NULL);
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272