c++ - Avoiding memory leak -
So I was learning Oop in C ++ and I thought it would be a good practice to write your own string class (for learning purposes)
, of course). I came up with a problem that I did not know how to solve. Here's some peace of code:
class string {char * str; Public: string (four consists * straw); ~ String (); String operator + (four consists * straw); }; String :: string (four * straw) {it-> Str = _strdup (str); } String: ~ string () {free (this-> str); } String String :: Operator + (Four Constant * Straw) {char * temp = (four *) malloc (strlen (str) + strlen (this-> str) + 1); Strcpy (temp, this-> string); Dome (temporary, str); Return temporary; } The problem here is that this piece of code will cause a memory leak. Returning from "Operator +", my constructor is called, which assigns more memory, gives temporary copies, and I can not find it in any way how can I free it.
return your operator + to string Is defined as, but you are returning a char * which means that the compiler is converting it inherently using the constructor, it copies the string, but the original is not free Does what you're leaking. There are many things that you can do to improve the code, as others have suggested, but to correct the actual leak, do this:
String String :: Operator + (Four Constant * Straw) {char * temp = (four *) malloc (strlen (str) + strlen (this-> str) + 1); Strcpy (temp, this-> string); Dome (temporary, str); String stratm (temporary); Free (temporary); Return SRTMP; }
Comments
Post a Comment