Search code examples
c++memory-managementmemory-leaks

freeing allocated memory returned from function in c++


I have a question that i cant find the answer.

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 cant free. keeping in mind that memory leaks arent good and should be avoided - is there a way to do this right way?

Tried to search internet with no result.

Considered creating list of pointers that were allocated from the function and free them somewhere later, but its not best/safe way as it is easy to mess.


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;
    }