简体   繁体   中英

how to free allocated parameter?

I got something like this:

ClassA& ClassA::operator>>(char*& string) {
    string = (char*)malloc(size);

    //read something in that string then return
    return *this;
}

Now i want to free the memory allocated in this function without losing the information stored.If i free it before the return i lose information. I tried to free it inside the constructor but the parameter is not known there or in another function. So how can I do it? I use valgrind to check memory leaks and it pointed me to this malloc.

first, using "malloc" is bad practice, in c++ (you should use new, even if it's for making a char array; use new char[size]);

if you must, add this pointer to a list of pointers this class is responsible for, and in the destructor of this class, go over that list and call delete for each (or free, if you choose to keep using malloc).

another option, is to call delete/free, where this function is being used (not as clean, and may result in memory leaks, as you came across).

as mentioned in another answer here, using string may also solve your problem (although, you'll need to rewrite the code that calls this function).

one other way, may be using a smart pointer. but that may be over complicating things for what you need here (as it means rewriting the code that calls this function).

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