C++ – Release Your Buffers

I am in the process of taking some 3rd party c++ source code, and converting it to VS2005. One thing I noticed over and over, is that when you are reading in file contents, you need to make sure to release the buffer, but with the length of the file as the parameter.

For example, this code:

CString myData;

if (file.Open(lpszFilename, CFile::modeRead))
{
DWORD dwLength = file.GetLength();

file.Read(myData.GetBuffer(dwLength), dwLength);
myData.ReleaseBuffer();

file.Close();
}

will throw an assertion when in debug mode

GetData.JPG
to fix, add the dwLength value to your ReleaseBuffer()

myData.ReleaseBuffer(dwLength);

if you run the bad code in release mode, nothing happens, which suprises me, you would think that the runtime would croak, but it doesn’t. Anyways, make sure to release your buffers.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s