I am extremely curious if returning a reference from a method can cause a memory leak. Below is the example situation.
class example
{
public:
vector<int> & get_vect()
{
return vect;
}
int & get_num()
{
return num;
}
private:
vector<int> vect;
int num;
};
void test_run(example & input)
{
int & test_val = input.get_num();
vector<int> & test_vect = input.get_vect();
}
int main()
{
example one;
test_run(one);
return 0;
}
My question is when test_val
and test_vect
get removed from the stack when test_run
exits. Does either test_vect
or test_val
get deleted thereby causing the object one to get corrupted?
A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code (i.e. unreachable memory). A memory leak has symptoms similar to a number of other problems and generally can only be diagnosed by a programmer with access to the program's source code.
How to avoid Memory Leak? Instead of managing memory manually, try to use smart pointers where applicable. use std::string instead of char *. The std::string class handles all memory management internally, and it's fast and well-optimized.
The main cause of memory leaks in an application is due to unwanted references. The garbage collector finds the memory that is no longer in use by the program and releases it back to the operating system for further allocation.
A C++ function can return a reference in a similar way as it returns a pointer. When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var. But you can always return a reference on a static variable.
No. References are aliases (or names) for something else. You can think of it as a never-owning pointer to something without pointer semantics (and their pitfalls, though references themselves have a few twists).
When the function test_run
exits, the references and only them are gone. What they referred to hasn't been touched memory-wise, it hasn't been deleted.
Moreover, as you're only dealing with variables that have automatic storage duration and don't involve dynamic memory during construction, you simply can't have memory leaks there. You could have other problems like trying to delete a pointer that points to such variable (trying that just yielded a core dump on coliru) but not leaks.
No. Why should it cause a memory leak, if you are not allocating memory with new
, which means on the heap? All your variables are allocated on the stack. References are just aliases for other variables.
C++ reference definition according to wikipedia
:
The definition of a reference in C++ is such that it does not need to exist. It can be implemented as a new name for an existing object.
There's also a paragraph talking about the difference between pointers and references.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With