不断增加物理内存Visual c++ CryptMsgClose和CryptReleaseContext

Increases physical memory continuously Visual C++ CryptMsgClose and CryptReleaseContext

本文关键字:CryptReleaseContext CryptMsgClose c++ 物理内存 Visual 不断增加      更新时间:2023-10-16

我使用c++和Visual Studio 2005。

我有一个项目,记忆在一个非常不正常的增加。当调试代码时,我意识到有几个部分对它有贡献。例如:

 // 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(int i=0; i<100000; ++i)
        {
            memoryUP( myfile._data, myfile._length );
        }
    }
    delete myfile;
    return 0;
}

当我运行这段代码时,内存不断上升"当调用cryptmsupdate"。我的分配错了吗?

我试图使用内存泄漏检测启用方法来检测内存泄漏,但什么也没有出现:

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
and
_CrtDumpMemoryLeaks();

Thanks in Advance

您必须按照获取资源的相反顺序释放资源:

 CryptAcquireContext();
 if (success)
 {
   CryptMsgOpenToDecode();
   if (success)
   {
      CryptMsgClose();
   }
   // else: nothing to close, opening failed
   CryptReleaseContext();
 }
 // else: nothing to release, acquisition failed

更深的嵌套结构依赖于外部的结构,并且可能锁定资源,因此在释放依赖的资源之后,只能释放先决的资源。

既然你标记了这个c++,我就会疏忽地提到这些事情应该用RIAA来处理,你应该创建一个类来负责资源。正如您在这个简单的示例中所看到的,编写正确的错误检查路径很快就会变得非常繁重,所以最好是让一个类在自己清理之后自动以正确的顺序进行清理,这样会更好,也更模块化。

我认为你应该在CryptReleaseContext之前调用CryptMsgClose

相关文章:
  • 没有找到相关文章