Junior — Middle
Explain what is meant by a memory leak in the context of programming.
sobes.tech AI
Answer from AI
Memory leak is a situation where a program allocates memory (for example, using malloc in C), but then does not free it after use. As a result, this memory remains occupied and unavailable for reuse, which over time can lead to exhaustion of available memory and decreased performance.
Example of a memory leak in C:
#include <stdlib.h>
void leak() {
int* ptr = malloc(sizeof(int) * 10);
// Use ptr
// But forget to call free(ptr);
}
Here, memory is allocated but not freed, leading to a leak.
In languages with automatic memory management (e.g., Java), leaks can occur if objects remain accessible through references even though they are no longer needed, preventing the garbage collector from freeing the memory.