码迷,mamicode.com
首页 > 数据库 > 详细

Mysql: Connect/C++ 使用过程中发现返回 std::string 造成的内存泄露

时间:2015-09-10 21:11:49      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

在使用 Connect/C++ ,测试时发现在调用 getString 出现了内存增长的情况。

      ConstructOutput();        //打印出当前内存
        for(int i=0;i<1000;++i)
        {
            prepareState.reset(con->prepareStatement("call test.testproc3(?)"));
            prepareState->setInt(1,1001);
            prepareState->executeUpdate();

            result.reset(prepareState->getResultSet());
            // 输出结果    
            while(result->next())
            {
                int id = result->getInt("id");
                string name = result->getString("name");  //这里注释掉就不增长了  
            }
            while (prepareState->getMoreResults())
                result.reset(prepareState->getResultSet());
        }
        ConstructOutput();

 

  ConstructOutput(); 函数 是打印当前内存的,实现见下面的头文件:

#pragma once

#define CRTDBG_MAP_ALLOC
#include <windows.h>
#include <tchar.h>
#include <crtdbg.h>
#include <stdlib.h>
#include <iostream>
#include <Psapi.h>
#pragma comment(lib,"psapi.lib")

#ifdef _DEBUG
#define malloc(s)           _malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__)
#define calloc(c, s)        _calloc_dbg(c, s, _NORMAL_BLOCK, __FILE__, __LINE__)
#define realloc(p, s)       _realloc_dbg(p, s, _NORMAL_BLOCK, __FILE__, __LINE__)

#define new                    new(_NORMAL_BLOCK,__FILE__,__LINE__)
#endif

#define DEFAULT_OUT_TITLE    \
    TEXT("缺页中断数  工作集(KB)  虚存(KB)  虚存峰值(KB)")
#define DEFAULT_OUTPUT_FORMAT    \
    TEXT("  %u    %u    %u    %u  ")

// 字节单位转换,向0取整
#define B2KB(x)    ((x) >> 10)

///////////////////////////////////////////////////////////////////////////////////

void ConstructOutput()
{
    PROCESS_MEMORY_COUNTERS pmc;
    std::cout<<DEFAULT_OUT_TITLE<<std::endl;
    if(!GetProcessMemoryInfo(GetCurrentProcess(),&pmc,sizeof(pmc)))return ;

    char output[512] = {0};
    _sntprintf(output,sizeof(output),DEFAULT_OUTPUT_FORMAT,
        (pmc.PageFaultCount),B2KB(pmc.WorkingSetSize),B2KB(pmc.PagefileUsage),B2KB(pmc.PeakPagefileUsage));
    std::cout<<output<<std::endl;
}

 

   内存增长后面定位在 getString() 函数上面。 

   原因是,我的dll是用 vs2010生成的。 但我调用的工程是 vs2003的工程。 而Connector/c++返回的是 std::string ,应该是编译器实现不一样导致内存泄露。

 

   跨平台使用stl果然要小心啊。

 

Mysql: Connect/C++ 使用过程中发现返回 std::string 造成的内存泄露

标签:

原文地址:http://www.cnblogs.com/sixbeauty/p/4799073.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!