Increases physical memory continuously Visual C++ CryptMsgClose and CryptReleaseContext
I am using C++ and Visual Studio 2005.
I have a project that memory Increases in a very abnormal. When debug the code I Realized That there are Several parts That Contribute to it. Like this for example:
// has to add crypt32.lib to link
#include <windows.h>
#define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
void memoryUP( const unsigned char *pData, int cData )
{
HCRYPTMSG msg = NULL;
HCRYPTPROV hProv = NULL;
CryptAcquireContext(&hProv,NULL,NULL,PROV_RSA_FULL,0);
msg = CryptMsgOpenToDecode(MY_ENCODING_TYPE,0,0,hProv,NULL,NULL);
if(!(CryptMsgUpdate( msg, pData, cData, TRUE)))
{
if(msg != NULL)
{
CryptMsgClose(msg);
msg = NULL;
}
}
if (hProv != NULL)
CryptReleaseContext(hProv,0);
if (msg != NULL)
{
CryptMsgClose(msg);
msg = NULL;
}
}
int main(int argc, char** argv)
{
MyFile myfile = myReadFile("c:\\file.p7s");
{
for(i开发者_如何学Pythonnt i=0; i<100000; ++i)
{
memoryUP( myfile._data, myfile._length );
}
}
delete myfile;
return 0;
}
When I run this code, the memory goes up continuously "when call CryptMsgUpdate". Am I deallocating wrong?
I tried to use Memory Leak Detection Enabling method to detect memory leak but nothing appears:
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
and
_CrtDumpMemoryLeaks();
Thanks in Advance
You have to release resources in reverse order of their acquisition:
CryptAcquireContext();
if (success)
{
CryptMsgOpenToDecode();
if (success)
{
CryptMsgClose();
}
// else: nothing to close, opening failed
CryptReleaseContext();
}
// else: nothing to release, acquisition failed
The deeper nested constructions depend on the outer ones and may lock up resources, so you can only release the prerequisite resources after you've released the dependent ones.
Since you tagged this C++, I would be remiss to mention that those sort of things should be handled with RIAA, and you should make a class that takes responsibility for the resource. As you can see even in this simple example, writing the correct error checking paths very quickly become onerous, so it'd be much better and more modular to have a class that cleans up after itself, which automatically happens in the correct order.
I think you should call CryptMsgClose before CryptReleaseContext.
精彩评论