Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make memory leak without using malloc?

This question is as in title: Is it possible to produce a memory leak without using any kernel specific means like malloc, new, etc?

What if I will make a linked list inside a function with lot of elements in there, and after it I'll exit from this function without cleaning a list. The list will be created without using any malloc calls, i.e.

struct list_head {
     struct list_head *next, *prev;
}

Can it be guaranteed that all resources will be freed after exiting from this function? So I can freely execute it a million times and nothing will be leaked?

Subject: If you not using any particular malloc or new calls you won't get a heap memory leak. Never. Is that right?

like image 562
Mikhail Kalashnikov Avatar asked Dec 08 '22 12:12

Mikhail Kalashnikov


1 Answers

A leak is always connected to a resource. A resource is by definition something that you acquire manually, and that you must release manually. Memory is a prime example, but there are other resources, too (file handles, mutex locks, network connections, etc.).

A leak occurs when you acquire a resource, but subsequently lose the handle to the resource so that nobody can release it. A lesser version of a leak is a "still-reachable" kind of situation where you don't release the resource, but you still have the handle and could release it. That's mostly down to laziness, but a leak by contrast is always a programming error.

Since your code never acquires any resources, it also cannot have any leaks.

like image 60
Kerrek SB Avatar answered Dec 11 '22 02:12

Kerrek SB