c++memory-managementmemory-leaks

freeing allocated memory returned from function in c++


If I have a function like this:

char* f1(char ch, int len) { 
    char* s1=new char[len+1); 
    for(int i; i<len; i++) s1[i]=ch; 
    s1[len]=0; 
}

and I call it like this:

char* str;
str=f1("A", 10);
std:cout << "Something " << str << std::endl;
delete[] str;

everything is ok, but if I want to use it shorter like this:

std:cout << "Something " << f1("A", 10) << std::endl;

I'll end up with allocated memory I can't free. Keeping in mind that memory leaks aren't good and should be avoided - is there a way to do this the right way?

I tried to search the internet with no result.

I considered creating a list of pointers that were allocated from the function and free them somewhere later, but it's not the best/safe way as it is easy to mess up.


Solution

  • You can use a std::unique_ptr like this:

    #include <memory>
    #include <iostream>
    
    typedef std::unique_ptr<char[]> MyPtr;
    
    MyPtr f1(char ch, int len) {
        MyPtr s1(new char[len+1]);
        for(int i=0; i<len; i++) s1[i]=ch;
        s1[len]=0;
        return s1;
    }
    
    int main()
    {
        std::cout << "Something " << f1('A', 10).get() << std::endl;
    }
    

    Background: the object returned from f1 gets destroyed at the end of the statement -- that is, after executing the line, when the ; is reached.

    Btw, I had to fix various minor typos in your code; in the future, just copy-paste your code into the question, instead of retyping it...

    Of course, at the end of the day, you should just be using std::string -- you are, after all, using C++...

    #include <iostream>
    #include <string>
    
    int main()
    {
        std::cout << "Something " << std::string(10, 'A') << std::endl;
    }