不断增加物理内存Visual C++;CryptMsgClose和CryptReleaseContext 我使用C++和Visual Studio 2005。< /P>
我有一个项目,记忆在非常不正常的情况下增长。当调试代码时,我意识到有几个部分对它有贡献。例如:不断增加物理内存Visual C++;CryptMsgClose和CryptReleaseContext 我使用C++和Visual Studio 2005。< /P>,c++,visual-c++,memory-management,C++,Visual C++,Memory Management,我有一个项目,记忆在非常不正常的情况下增长。当调试代码时,我意识到有几个部分对它有贡献。例如: // 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
// 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;
}
//必须将crypt32.lib添加到链接
#包括
#定义MY_ENCODING_类型(PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
void memoryUP(常量无符号字符*pData,int-cData)
{
HCRYPTMSG msg=NULL;
HCRYPTPROV hProv=NULL;
CryptAcquireContext(&hProv,NULL,NULL,PROV_RSA_FULL,0);
msg=CryptMsgPentodeCode(我的编码类型,0,0,hProv,NULL,NULL);
if(!(CryptMsgUpdate(msg、pData、cData、TRUE)))
{
如果(msg!=NULL)
{
CryptMsgClose(msg);
msg=NULL;
}
}
如果(hProv!=NULL)
CryptReleaseContext(hProv,0);
如果(msg!=NULL)
{
CryptMsgClose(msg);
msg=NULL;
}
}
int main(int argc,字符**argv)
{
MyFile MyFile=myReadFile(“c:\\file.p7s”);
{
对于(int i=0;i,您必须按获取资源的相反顺序释放资源:
CryptAcquireContext();
if (success)
{
CryptMsgOpenToDecode();
if (success)
{
CryptMsgClose();
}
// else: nothing to close, opening failed
CryptReleaseContext();
}
// else: nothing to release, acquisition failed
更深层次的嵌套构造依赖于外部构造,可能会锁定资源,因此只有在释放依赖的资源之后才能释放先决条件资源
<> P>既然你标记了这个C++,我会很不高兴地提到,这些事情应该用RIAA来处理,你应该做一个对资源负责的类,正如你在这个简单的例子中所看到的,正确的错误检查路径的编写很快变得繁琐,所以它会更好地和更模块化地拥有一个类在其自身之后进行清理,这会自动按正确的顺序发生。我认为您应该在CryptReleaseContext之前调用CryptMsgClose。只是一个猜测,您不应该按照获取资源的相反顺序释放资源吗?也就是说,CryptMsgClose
应该在CryptReleaseContext
之前。您是说g每次调用memoryUP()时,内存使用量都会增加?如果注释掉CryptMsgUpdate()调用,会发生什么情况?-每次都会增加内存吗?为什么CryptMsgClose(msg)会增加;block打了两次电话?@Kerrek SB.顺序相反,没有内存占用。谢谢。如何为你+1?@Nick Shaw,是的。如果我评论内存没有占用。我会按相反顺序解决它。谢谢
CryptAcquireContext();
if (success)
{
CryptMsgOpenToDecode();
if (success)
{
CryptMsgClose();
}
// else: nothing to close, opening failed
CryptReleaseContext();
}
// else: nothing to release, acquisition failed