Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reason for memory leakage in C C++

what are the reasons for memory leakage in C C++ (except the usual allocating memory and forget to deallocate it)

like image 312
ashmish2 Avatar asked Dec 15 '10 06:12

ashmish2


People also ask

What is the main cause of memory leaks?

DEFINITION A memory leak is the gradual deterioration of system performance that occurs over time as the result of the fragmentation of a computer's RAM due to poorly designed or programmed applications that fail to free up memory segments when they are no longer needed.

What causes a memory leak in C?

Memory leaks occur when new memory is allocated dynamically and never deallocated. In C programs, new memory is allocated by the malloc or calloc functions, and deallocated by the free function.


1 Answers

If an exception is raised between allocation and deallocation, memory leak will occur.

void f1() {
    int* ptr = new int;

    // do something which may throw an exception

    // we never get here if an exception is thrown
    delete ptr;
}

Each time f1 terminates with an exception, 4 bytes are leaked (assuming int is 4 byte).

like image 87
watson1180 Avatar answered Sep 20 '22 17:09

watson1180