zoukankan      html  css  js  c++  java
  • Mysql: Connect/C++ 使用过程中发现返回 std::string 造成的内存泄露

    在使用 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果然要小心啊。

  • 相关阅读:
    浅谈工业无线技术之天线
    防护等级
    PROFINET如何实现实时性
    2020,我又回来了
    关于ReentrantLock和Condition的用法
    当你在试衣间试衣服,请你务必想起wait()与notify()
    用生活例子来解释Java synchronized块
    关于textview显示特殊符号居中的问题
    扯一扯我的2016
    国庆的这6天
  • 原文地址:https://www.cnblogs.com/sixbeauty/p/4799073.html
Copyright © 2011-2022 走看看