Code Smell 322 - Don't Keep Request-owned Pointers in Long-lived Variables

https://hackernoon.imgix.net/images/RIiBoPtpMiRsMKX3dnzl5gb1Urj1-8g836tr.png

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 πŸ˜”

Solutions πŸ˜ƒ

  1. Scope state per request
  2. Centralize state ownership
  3. Initialize before early consumers
  4. Clear references before freeing
  5. Cover every exit path
  6. Block late writes
  7. 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

Read more