Home > Articles > Security > Network Security

Memory Hygiene in C and C++: Safe Programming with Risky Data

📄 Contents

  1. When Bad Things Happen to Good Programs
  2. Guidebook to Memory Mis-Pointing
  3. Where Are We Now?
  • Print
  • + Share This
Memory management is scary. It should be: A lot can go wrong—often very wrong. But a moderately experienced C or C++ programmer can learn and understand memory hazards completely. Once you have that knowledge, you should feel only confidence, not fear.
Like this article? We recommend

When you read a news alert about a new exploit having been found that "cracks" a widely used application, a crucial memory error is likely to be at the base of the problem. When a program "ages"—when it can't be left running more than a day without crashing, slowing down catastrophically, or interfering with other programs—that's likely to be a memory fault.

This is a serious point, and one that's hard for non-programmers to understand. Outsiders think we spend our time doing mathematical formulas or teaching computers to solve Aristotelian syllogisms ("Socrates is a man, therefore it's time to launch the missile"). This isn't true, of course; a great deal of our time goes to such tedium as laying out data structures efficiently, or incrementing by one. Because human memory works on an associative model, though, civilians don't have the background to appreciate this work. Memory management is much of what makes C programming difficult, and, from what I can tell, at the heart of many (perhaps most) reported security exploits.

I often work with a range of so-called high-level languages, almost all of which share a secret: A big part of their productivity advantage over C is simply the convenience of their memory management. One of the reasons that this is so important is the poor locality of memory problems. Traditional debugging techniques for correction of arithmetic or logical errors help little when tracking down memory problems, because it so often happens that a memory mismanagement in one module produces only intermittent symptoms, and those symptoms may appear in a distant module.

The good news, though, is that it's possible to manage memory correctly. This article is the first in a three-part series on how to acquire that skill. We'll look at recipes that help you code more secure and reliable C-based applications.

  • + Share This
  • 🔖 Save To Your Account