Code Smell 322 - Don't Keep Request-owned Pointers in Long-lived Variables
Your request is gone. Your pointer is not.
TL;DR: Don't keep request-owned pointers in long-lived variables, or the next request reads freed memory.
Problems π
- Use after free on stale request memory
- Remote code execution
- Hidden side effects
- Stale state crosses into a later request
- Stale values, like a bad cache
- Tests miss cross-request failures
Solutions π
- Scope state per request
- Centralize state ownership
- Initialize before early consumers
- Clear references before freeing
- Cover every exit path
- Block late writes
- Test consecutive worker requests
Refactorings βοΈ
Context π¬
A server process can live for hours and handle many requests in a row, while a request may last milliseconds.
When you store a request's pointer in a process-wide variable, you tie two lifetimes together without saying so.
The request ends and the runtime frees its memory, but the variable keeps the address.
The next request starts, and some code runs before initialization...
Copyright of this story solely belongs to hackernoon.com. To see the full text click HERE