Memory Leak - A Simple Example in C

A Simple Example in C

The following C function deliberately leaks memory by losing the pointer to the allocated memory. Since the program loops forever calling the memory allocation function, malloc, but without saving the address, it will eventually fail (returning NULL) when no more memory is available to the program. Because the address of each allocation is not stored, it is impossible to free any of the previously allocated blocks. It should be noted that, generally, the operating system delays real memory allocation until something is written into it. So the program ends when virtual addresses run out of bounds (per process limits or 2 to 4 GiB on IA-32 or a lot more on x86-64 systems) and there may be no real impact on the rest of the system.

#include int main(void) { /* this is an infinite loop calling the malloc function which * allocates the memory but without saving the address of the * allocated place */ while (malloc(50)); /* malloc will return NULL sooner or later, due to lack of memory */ return 0; /* free the allocated memory by operating system itself after program exits */ }

Read more about this topic:  Memory Leak

Famous quotes containing the word simple:

    I like a thing simple but it must be simple through complication. Everything must come into your scheme, otherwise you cannot achieve real simplicity.
    Gertrude Stein (1874–1946)