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.
6
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.
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;
}
There are several issues in your code:
-
f1
is supposed to return achar*
but does not contain areturn
statement (likereturn s1;
). -
You call
f1
withf1("A", 10)
. But the first parameter is supposed to be achar
and “A” isn’t. It should bef1('A', 10)
instead. -
In C++ it not not recommended to use raw C arrays. One of the problems with it is the need for manual memory management that you encounter. It is better to use standard library classes like
std::vector
(for a general purpose dynamic array), or in this case of an null-terminated array of characters – usestd::string
. -
std::string
already has a constructor that accepts a length and a character and creates a string like yourf1
attempts to do, so you can simply use:std::cout << "Something " << std::string(10, 'A') << std::endl;
Output:
Something AAAAAAAAAA
Live demo