If not does that mean that I would have to end each function by deleting all local variables if I wanted to prevent 100% of memory leak?
Dynamically allocated memory using malloc, realloc, new, and new[] must be deleted. These are in heap memory. Others would get automatically deallocated.
The local variables that are allocated on stack, i.e. without using memory allocation functions or operators like malloc
and new
, are deleted automatically. All other variables have to be deleted by using delete
as they are stored on heap.
If you manually allocate memory you must deleted it whenever you need,
Example:
char* foo()
{
char* manually_allocated_char = new char(); // this will 'live' outside the function
char autamically_allocated = 'a'; // this will be 'deleted'
return manually_allocated_char;
}
void main()
{
char* a_new_char = foo();
delete a_new_char; // You must free memory you have allocated for not having memory leaks
}
All objects have an associated storage duration. A storage duration describes how long the storage for an object is kept around. Local variables that are not references introduce an object with automatic storage duration, which means that the storage of those objects is automatically destroyed at the end of its scope.
Reference type variables do not introduce an object and may not even require storage of their own, but they still have storage duration (§3.7/3). If a reference does require storage, it will be released according to the reference's storage duration.
As such, any kind of local variable declaration will not leak. In fact, you cannot delete
an object with automatic storage duration. That is only used for objects with dynamic storage duration, which are allocated using new
.