Memory Leak in C

Thread Starter

gogo00

Joined Oct 28, 2023
37
How does memory leak happen in C language? In my understanding suppose If we have only 8 bytes of memory and the program tries to store three integers, each occupying 4 bytes, Thats memory leak. does that result in a memory leak? What are your thoughts on this?
 

Papabravo

Joined Feb 24, 2006
21,225
Kind of depending on how you got the memory in the first place. Memory leaks happen in the process of dynamic storage allocation. Usually this is the result of mismanaging pointers leading to a situation where you have pointers to memory that you have freed or memory that you have not allocated. Read the wiki for further information.

Memory leak - Wikipedia
 

BobTPH

Joined Jun 5, 2013
8,937
A memory leak is when you fail to free all the memory you allocate. Running out of memory may or may not be due to leaks.
 

dl324

Joined Mar 30, 2015
16,900
In my understanding suppose If we have only 8 bytes of memory and the program tries to store three integers, each occupying 4 bytes, Thats memory leak. does that result in a memory leak?
That's not what a memory leak is.

A memory leak occurs when you don't manage memory you allocate correctly (and you're not using a language that does garbage collection for you).
 
Last edited:

WBahn

Joined Mar 31, 2012
30,038
How does memory leak happen in C language? In my understanding suppose If we have only 8 bytes of memory and the program tries to store three integers, each occupying 4 bytes, Thats memory leak. does that result in a memory leak? What are your thoughts on this?
What you describe is not a memory leak. If you try to store 12 bytes of data when you only have 8 bytes available, you have simply un out of memory. The details depend on where you try to store those three integers. If allocated 8 bytes for an array of integers intended to hold two values and you try to store three there, you have a buffer overflow. The behavior when you do that is undefined. If your process only has eight bytes assigned to it and you try to write outside that space (and you are running under a modern operating system) the OS will kill your program for committing a segmentation fault.

A memory leak happens when you allocate memory and then fail to deallocate it before changing the value of the pointer that used to point to it.
 

WBahn

Joined Mar 31, 2012
30,038
Kind of depending on how you got the memory in the first place. Memory leaks happen in the process of dynamic storage allocation. Usually this is the result of mismanaging pointers leading to a situation where you have pointers to memory that you have freed or memory that you have not allocated. Read the wiki for further information.

Memory leak - Wikipedia
Pointers to memory that has been freed is not a memory leak, but rather a dangling pointer (aka, a wild pointer). It is essentially the exact opposite of a memory leak. Both are examples of memory safety violations.
 
Top