# Memory Leaks & Dangling Pointers — C Programming

Source: https://www.geekswithgeeks.com/en/c/c-memory-leaks

> What goes wrong when heap memory isn't managed carefully.

## A leak: memory you can never reach again

If you overwrite or lose the only pointer to a `malloc`'d block without freeing it first, that memory stays reserved forever — a **memory leak**. Long-running programs (servers, games) leaking repeatedly will eventually run out of memory.

## A dangling pointer

After `free`, the pointer still holds the old address — using it is undefined behavior, even though the compiler won't stop you.

```c
int *p = malloc(sizeof(int));
*p = 42;
free(p);

printf("%d\n", *p); // BUG: use-after-free
p = NULL;             // now safe: NULL is checkable
```

## Rule of thumb

Every `malloc`/`calloc` should have exactly one matching `free`. Set the pointer to `NULL` right after freeing so an accidental reuse fails loudly instead of silently corrupting memory.

**Quiz:** What should you do to a pointer immediately after calling free() on it?

- [x] Set it to NULL
- [ ] Call free() on it again
- [ ] Nothing, it's fine to keep using it

*Answer:* Set it to NULL. Setting it to NULL prevents accidental use-after-free bugs.
