简体   繁体   中英

How do I free the memory occupied by variable that is being returned (using C++, in a class, destructor)?

Example code:

class Myclass
{
    char * function(const char *x, const char *y)
    {
        char *a, *b, *c;
        *a = strdup(x);
        *b = strdup(y);
        *c = (char *) malloc(strlen(a) + strlen(b) + 1);
        ...
        ...
        free(a);
        free(b);
        return c;
    }
};

How do I free the memory occupied by c ? When I try to do it in the destructor, it says use of undeclared identifier c . Is there anyway to free the memory without allocating the memory in a constructor?

A class destructor should only be responsible for freeing the memory allocated by constructors for that class . That's what is ownership.

Also, c in your code is local to function so it ceases to exist beyond that function ie a sure shot memory leak unless you are returning c from this function and making sure that caller calls delete/free on that memory. But this puts much burden on usability department.

answer: stop!

and remember you're writing in c++ where the correct thing to do is leave memory management to the standard library and return values rather than pointers.

class Myclass
{
    std::string function(const char *x, const char *y)
    {
        // no more overhead than strdup - and much safer!
        std::string a(x), b(y);

        // what I shall return
        std::string c;

        // un-necessary, but can improve efficiency
        c.reserve(a.size() + b.size());

        // perform my complex string algorithm
        //... for example, concatenate into c:
        c = a + b;

        // return my result    
        return c;
    }
};

now call like so:

{
  MyClass x;
  auto s = x.function("hello", "world");

  // s is a std::string. if I *really* want a pointer, I can...
  const char* p = s.c_str();

  // note: no need to free *anything*
}

You cannot call free(c); in the destructor unless c is a member variable, which is what the compiler is telling you.

In this case, you have to make sure that the caller of MyClass::function calls free on the returned value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM