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.
Rif Fox is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.