Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When a function ends are its local variables deallocated?

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?

like image 810
user3169700 Avatar asked Feb 17 '14 15:02

user3169700


Video Answer


4 Answers

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.

like image 78
Shubham Avatar answered Oct 22 '22 03:10

Shubham


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.

like image 37
Joseph Mansfield Avatar answered Oct 22 '22 03:10

Joseph Mansfield


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
}
like image 32
Netwave Avatar answered Oct 22 '22 03:10

Netwave


Dynamically allocated memory using malloc, realloc, new, and new[] must be deleted. These are in heap memory. Others would get automatically deallocated.

like image 28
Sks Sapare Avatar answered Oct 22 '22 03:10

Sks Sapare