Search code examples
c++binary-datafreadfile-read

fread gives BadPtr when done in a new process


I have written a C++ Dll which has two functions, one writes a binary file to disk and and other reads that file from disk and load into memory.

//extremely simplified code looks like this

bool Utilities::WriteToBinary(wstring const fileName)
    {
    //lot of code

    DWORD size = //get size of data to write
    LPBYTE * blob = new LPBYTE[size];
    WriteDataToMemoryBlob(blob, & size);

    FILE * pFile;
    if(0 != _wfopen_s (&pFile , fileName.c_str() , L"wb" ))
        {
        //do something
        return false;
        }

    fwrite (blob,  1, size , pFile );
    fclose (pFile);

    delete[] blob;
    return true;
    }

bool Utilities::ReadDataFromDisk(wstring const fileName)
    {    
    long fileSize = GetFileSize(fileName);
    FILE * filePointer;
    if(0 != _wfopen_s (&filePointer, fileName.c_str() , L"rb" ))
        return false;

    //read from file
    LPBYTE * blobRead = new LPBYTE[fileSize];
    fread (blobRead, 1, fileSize , filePointer );
    fclose (filePointer);

    //rest of the code...

Problem I have created another C++ project which call these DLL methods for testing.

Problem which is driving me crazy is that when I call WriteToBinary and ReadDataFromDisk consecutively inside same program they work perfectly fine. But when I call WriteToBinary at one time and let the program exit and call ReadDataFromDisk next time and give it path of file written earlier by WriteToBinary, I get a BadPtr in blobRead after doing fread.

I have tried my best to make sure there are no shared or static data structures involved. Both methods are totally independent.

Any idea what might be causing this?


Solution

  • A mistake is the allocation of the array as LPBYTE is a BYTE* so the:

    LPBYTE * blobRead = new LPBYTE[fileSize];
    

    Is allocating an array of BYTE*, not an array of BYTE. Change to:

    BYTE* blobRead = new BYTE[fileSize];
    

    To avoid dynamic allocation you could use a std::vector<BYTE> instead:

    std::vector<BYTE> blobRead(fileSize);