Wednesday, March 9, 2011

Error: Attempted to Read or Write Protected Memory

This error is displayed when trying to open or close a window with a .NET addin on it.  It is usually followed my the error
BAD_MEM_HANDLE

or simply the dreaded "The application has to close" error

Then GP crashes.

The causes are data buffer related.  Either there is a table buffer that has been opened in .NET that has not been closed, or a reader has not been closed.

The reader error can be hard to detect when reading the code.  For example, the following code will result in the reader being left open.

OdbcDataReader reader = oCmd.ExecuteReader();


if (reader.Read())
{
return  reader.GetString(0);
}
else
{
return string.Empty;
}

 
The reader can't be closed before the return statement, since the reader is needed for the return value.
 
To fix it, we have the take the long way around and store the return value before closing the reader.
 
OdbcDataReader reader = oCmd.ExecuteReader();

string result = "";
if (reader.Read())
{
result = reader.GetString(0);
}
else
{
result= string.Empty;
}
if (!reader.IsClosed)
{
reader.Close();
}
return result;

 
So the lesson learned here is that when working with readers, it is a good idea to store your reader results and close the reader before operating on them.. That way you won;t try to take a shortcut like the first example.

Did this help you?  If so, please leave a comment!

No comments:

Post a Comment

SQL 2022 TSQL snapshot backups!

  SQL 2022 now actually supports snapshot backups!  More specifically, T-SQL snapshot backups. Of course this is hardware-dependent. Here ...