int * myFun(const int & a)
{
int * c = new int(a);
int b = *c;
return &b;
}
1.How to intepret (const int & a)
and new int (a)
, what does it do?
2.Could you explain to me why there is a memory leak?
int * myFun(const int & a)
{
int * c = new int(a);
int b = *c;
return &b;
}
1.How to intepret (const int & a)
and new int (a)
, what does it do?
2.Could you explain to me why there is a memory leak?
You may want to pick a beginner book from The Definitive C++ Book Guide and List, read it through and then start again.
On to your questions:
const int & a
is a const reference to an int
, named a
. Basically, it means something that points to another int variable somewhere, and behaves just like that int, except you can't change its value
new int (a)
means you dynamically allocate memory somewhere on the heap for an int variable, and initialize that variable with the value a
. This expression returns the address of the variable you just created
Why is there a memory leak ? You allocate memory with the new int(a)
statement, but never release it. This should be done with:
delete c;
before the end of your function.
As noted in the comments, this function has undefined behavior in the return statement, since you return the address of a local variable (You may need to actually read that C++ beginner book to understand what that means).
Judging by the code, you are using c++
You get a new pointer c
with the value of a
then you make b
, with the same value as c
, you return b
, leaving c
as the leak because nothing points to c
anymore.
At then end:
a
is the const b
is the value of c
, which is the value of a
c
is a pointer to a new variable that is no longer referenced in your code