草庐IT

c++ - 在函数内释放动态内存

coder 2024-02-07 原文

第一次在这里注册帐户,但我非常喜欢这个网站。

我正在尝试创建一个函数来接收一个 const char 数组并返回该数组的一部分。该函数与数组一起接收两个值,指示要提取的部分中第一个字符的索引和最后一个字符的索引。

关于我正在尝试的棘手部分是我正在创建一个临时数组变量来将这部分保存在一个函数中并且鉴于该部分的大小不能保证是一个常量我正在使用动态分配必要空间的内存,这就是我遇到问题的地方。

只要函数返回任何信息,函数就会结束,程序就没有机会释放备用内存。如果我删除变量,我将无法返回信息。

我尝试创建一个单独的指针变量来指向形成后的信息,但是一旦内存被释放,信息似乎就无法恢复。

有问题解除分配的程序:

char* seperateString(const char* a, int b, int c) {

                // This is simply to assure that I don't allocated a negative size
        if (b < c) {
                cout << "***Error with \"seperateString\" function***" << endl << endl;
                return '\0';
        }

        char* seperated = new char[c - b + 2];

        int i = 0;
        int j = b;

        for (; i <= c - b; i++)
                seperated[i] = a[j++];

        seperated[i] = '\0';

        char* send = seperated;
        delete[] seperated;

        return send;
}

int main() {
        cout << "Program Iniciated." << endl << endl;

        const int a = 6, b = 11;


        const char* toBeSeperated = "Hello there, I have missed you.";
        char *ari = seperateString(toBeSeperated, 6, 11);

        cout << "Sentence is: " << toBeSeperated << endl << endl
            << "Extracted portion is: " << ari << endl << endl;

        cin.get();
        return 0;
}

程序在主函数中按预期工作。

int main() {
        cout << "Program Iniciated." << endl << endl;

            // variable a and b hold the beginning and last index values of the portion 
            // that is wanted to extract. 
        const int a = 6, b = 11;


            // This is an example sentence  |------| this is the portion being extracted.
        const char* toBeSeperated = "Hello there, I have missed you.";

            // variable holding extracted portion.
            // created with the size necessary to hold the portion plus a \0.
        char* seperated = new char[b  -a  +2];
                                                                //Given that a and b are index values 1 has to be added for size
                                                                //Additionally an extra space is require for \0

            //i is held outside the for loop to allow to access it after it completes the cycle
          //so it's able to assing \0 after the last character.
        int i = 0;

          //j holds the value of the first index
        int j = a;

        for (; i <= b - a; i++)
                seperated[i] = toBeSeperated[j++];

        seperated[i] = '\0';

        cout << "Sentence is: " << toBeSeperated << endl << endl
                << "Extracted portion is: " << seperated << endl << endl;

        delete[] seperated;
        cin.get();
        return 0;
}

最后,这是为了防止内存泄漏。

最佳答案

正如您所指出的,我们必须有实际存储函数结果的内存,因此我们不能在返回之前释放动态分配的数组。这给我们留下了两个选择:

  1. 在我们调用之前分配内存,并向被调用函数提供指向该内存的指针和大小(不够优雅)
  2. 确保我们以安全的方式传回指向已分配内存的指针

然而,在这两种情况下,我们都必须确保手动释放内存。智能指针非常适合这种用例,特别是 std::unique_ptr .

这是一个正常运行的程序:

#include <iostream>
#include <memory>

std::unique_ptr<char[]> seperateString(const char* a, int b, int c) {
    using namespace std;
    // This is simply to assure that I don't allocated a negative size
    if (c < b) {
        cout << "***Error with \"seperateString\" function***" << endl << endl;
        return '\0';
    }

    auto seperated = std::unique_ptr<char[]>(new char[c - b + 2]);

    int i = 0;
    int j = b;

    for (; i <= c - b; i++)
        seperated[i] = a[j++];

    seperated[i] = '\0';

    return seperated;
}

int main() {
    using namespace std;
    cout << "Program Iniciated." << endl << endl;

    const int a = 6, b = 11;


    const char* toBeSeperated = "Hello there, I have missed you.";
    auto ari = seperateString(toBeSeperated, 0, 5);

    cout << "Sentence is: " << toBeSeperated << endl << endl
        << "Extracted portion is: " << ari.get() << endl << endl;

    cin.get();
    return 0;
}

唯一指针获取动态分配资源的所有权,并在资源本身在离开作用域时被销毁时释放(即解除分配)资源。

函数中seperateString , 我们构建了 unique_ptr通过运算符 new[] 指向动态分配的字符数组的指针.从这一点开始,我们不需要管理动态分配的内存,因为它绑定(bind)到智能指针的生命周期 seperated .每当seperated被销毁,其析构函数将调用运算符 delete[]在构造时分配给它的数组指针上。

等等,seperated在函数返回时被销毁,那么我们不是回到原点,因为在我们开始在调用代码中使用它之前释放了内存吗?不,因为我们要返回 unique_ptr<char[]>按值,编译器将资源的所有权从函数本地 seperated 移出指向调用站点本地的唯一指针 ari唯一指针,通过移动构造函数构造它。现在函数调用中分配的内存的命运与 ari 的生命周期相关。 ,当它超出范围时,内存将被释放而不会泄漏。

关于c++ - 在函数内释放动态内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57368729/

有关c++ - 在函数内释放动态内存的更多相关文章

  1. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  2. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  3. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  4. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  5. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  6. ruby-on-rails - Ruby 中的内存模型 - 2

    ruby如何管理内存。例如:如果我们在执行过程中采用C程序,则以下是内存模型。类似于这个ruby如何处理内存。C:__________________|||stack|||------------------||||------------------|||||Heap|||||__________________|||data|__________________|text|__________________Ruby:? 最佳答案 Ruby中没有“内存”这样的东西。Class#allocate分配一个对象并返回该对象。这就是程序

  7. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  8. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  9. C51单片机——实现用独立按键控制LED亮灭(调用函数篇) - 2

    说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时

  10. ruby-on-rails - 将字符串转换为 ruby​​-on-rails 中的函数 - 2

    我需要一个通过输入字符串进行计算的方法,像这样function="(a/b)*100"a=25b=50function.something>>50有什么方法吗? 最佳答案 您可以使用instance_eval:function="(a/b)*100"a=25.0b=50instance_evalfunction#=>50.0请注意,使用eval本质上是不安全的,尤其是当您使用外部输入时,因为它可能包含注入(inject)的恶意代码。另请注意,a设置为25.0而不是25,因为如果它是整数a/b将导致0(整数)。

随机推荐