首页 > 解决方案 > 在 C++ 中使用 gdb 进行内存转储时的内存泄漏

问题描述

我在 C++ 中使用 gdb 的内存转储出现内存泄漏。我无法弄清楚内存泄漏的原因,我已经共享了我正在使用的代码。使用字符串构造函数初始化字符串时,何时释放字符串的内存?

代码-

#include<bits/stdc++.h>
using namespace std;

string getpass(string mypass)
{
    string my="";
    for(int i=0;i<mypass.length();i++)
    {
        my+= mypass[i]+1;
    }
    
    return my;
}

string all()
{
    string mypass = "shivam";
    string rdpCommand;
    rdpCommand = string("/opt/xfreerdp ") + string(" /ppppp:'")+getpass(mypass)+ string("' ");
    rdpCommand.clear();
    rdpCommand.shrink_to_fit();
            
    string command ="";
    return command;
}

    
int main(){
     
     string t=all();
     sleep(100);    //using sleep so the execution doesn't terminate and I can take memory dump
         
}

我用来进行内存转储的脚本-

#!/bin/bash

grep rw-p /proc/$1/maps \
| sed -n 's/^\([0-9a-f]*\)-\([0-9a-f]*\) .*$/\1 \2/p' \
| while read start stop; do \
    gdb --batch --pid $1 -ex \
        "dump memory $1-$start-$stop.dump 0x$start 0x$stop"; \
done

运行上面的脚本sudo ./script.sh [pid_of_process]

显示内存转储的屏幕截图 -

显示内存转储的屏幕截图

编辑:我尝试了 OpenSSL 保护字符串的方法,但它没有用,并尝试编写分配器和释放器,但它在 linux 中给出错误。 两个答案都在此链接中。如何安全地清除 std::string?

标签: c++linuxmemory-leaksgdb

解决方案


推荐阅读