0

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?

0

1 Answer 1

3

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);
2
  • I dont think I understand, why is it working when called in same program then? Commented Jan 12, 2013 at 9:05
  • @HarisHasan pure [bad] luck, would anyway be better if you used a vector instead.
    – AndersK
    Commented Jan 12, 2013 at 9:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.