encyclopegia.org

Defensive programming

Defensive programming is a form of defensive design intended to develop programs that are capable of detecting potential security abnormalities and make predetermined responses. It ensures the continuing function of a piece of software under unforeseen circumstances. Defensive programming practices are often used where high availability, safety, or security is needed. Defensive programming is an approach to improve software and source code, in terms of: * General quality – reducing the number of software bugs and problems. * Making the source code comprehensible – the source code should be readable and understandable so it is approved in a code audit. * Making the software behave in a predictable manner despite unexpected inputs or user actions. Overly defensive programming, however, may safeguard against errors that will never be encountered, thus incurring run-time and maintenance costs.

Defensive programming is a form of defensive design intended to develop programs that are capable of detecting potential security abnormalities and make predetermined responses. It ensures the continuing function of a piece of software under unforeseen circumstances. Defensive programming practices are often used where high availability, safety, or security is needed. Defensive programming is an approach to improve software and source code, in terms of: General quality – reducing the number of software bugs and problems. Making the source code comprehensible – the source code should be readable and understandable so it is approved in a code audit. Making the software behave in a predictable manner despite unexpected inputs or user actions. Overly defensive programming, however, may safeguard against errors that will never be encountered, thus incurring run-time and maintenance costs. int risky_programming(char *input) { char str[1000]; // ... strcpy(str, input); // Copy input. // ... } The function will result in undefined behavior when the input is over 1000 characters. Some programmers may not feel that this is a problem, supposing that no user will enter such a long input. This particular bug demonstrates a vulnerability which enables buffer overflow exploits. Here is a solution to this example: int secure_programming(char *input) { char str[1000+1]; // One more for the null character. // ... // Copy input without exceeding the length of the destination. strncpy(str, input, sizeof(str)); // If strlen(input) >= sizeof(str) then strncpy won't null terminate. // We counter this by always setting the last character in the buffer to NUL, // effectively cropping the string to the maximum length we can handle. // One can also decide to explicitly abort the program if strlen(input) is // too long. str[sizeof(str) - 1] = '\0'; // ... } const char* trafficlight_colorname(enum traffic_light_color c) { switch (c) { case TRAFFICLIGHT_RED: return "red"; case TRAFFICLIGHT_YELLOW: return "yellow"; case TRAFFICLIGHT_GREEN: return "green"; } return "black"; // To be handled as a dead traffic light. } Offensive programming const char* trafficlight_colorname(enum traffic_light_color c) { switch (c) { case TRAFFICLIGHT_RED: return "red"; case TRAFFICLIGHT_YELLOW: return "yellow"; case TRAFFICLIGHT_GREEN: return "green"; } assert(0); // Assert that this section is unreachable. } if (is_legacy_compatible(user_config)) { // Strategy: Don't trust that the new code behaves the same old_code(user_config); } else { // Fallback: Don't trust that the new code handles the same cases if (new_code(user_config) != OK) { old_code(user_config); } } Offensive programming // Expect that the new code has no new bugs if (new_code(user_config) != OK) { // Loudly report and abruptly terminate program to get proper attention report_error("Something went very wrong"); exit(-1); } ===Other ways of securing code=== One of the most common problems is unchecked use of constant-size or pre-allocated structures for dynamic-size data such as inputs to the program (the buffer overflow problem). This is especially common for string data in C . C library functions like gets should never be used since the maximum size of the input buffer is not passed as an argument. C library functions like scanf can be used safely, but require the programmer to take care with the selection of safe format strings, by sanitizing it before using it. Encrypt/authenticate all important data transmitted over networks. Do not attempt to implement your own encryption scheme, use a proven one instead. Message checking with a hash or similar technology will also help secure data sent over a network. ====The three rules of data security==== All data is important until proven otherwise. All data is tainted until proven otherwise. All code is insecure until proven otherwise. You cannot prove the security of any code in userland, or, more commonly known as: "never trust the client". These three rules about data security describe how to handle any data, internally or externally sourced: All data is important until proven otherwise - means that all data must be verified as garbage before being destroyed. All data is tainted until proven otherwise - means that all data must be handled in a way that does not expose the rest of the runtime environment without verifying integrity. All code is insecure until proven otherwise - means that all systems should be presumed insecure. For example, inputs must be handled as though they are malicious (e.g. SQL injection), and databases should be presumed to be compromised (which is why passwords are salted). ====More Information==== If data is to be checked for correctness, verify that it is correct, not that it is incorrect. Design by contract Assertions (also called assertive programming) ==See also== Computer security ==External links== CERT Secure Coding Standards

References

No reference rows published for this article.

Cite this article

MLA

"Defensive programming." encyclopegia.org, 2026, https://encyclopegia.org/wiki/defensive-programming. Accessed 24 November 2026.

Chicago

"Defensive programming." encyclopegia.org. Accessed November 24, 2026. https://encyclopegia.org/wiki/defensive-programming.

APA

encyclopegia.org. (2026). Defensive programming. Retrieved November 24, 2026, from https://encyclopegia.org/wiki/defensive-programming

Accessed November 24, 2026 · CC BY-SA 4.0 · citation page · JSON

Related articles

Marlinespike hitch

enwiki · references available

Geography of Uganda

enwiki · references available

Homestar Runner

enwiki · references available

Gladius

enwiki · references available

Sydney, Nova Scotia

enwiki · references available

Medicare (Australia)

enwiki · references available

Prototype-based programming

enwiki · references available

Event-driven programming

enwiki · references available
CC BY-SA 4.0 · share-alike · https://en.wikipedia.org/w/index.php?oldid=1372731078 · 0.5 · snapshot enwiki-001372731078

Cite · JSON · Search

Related services and records

Services

  • Estate — measured countries, lanes and facts
  • Intel — live corroborated events
  • Legal — statutes, cases and citations
  • Encyclopedia — articles with inline sources
  • Space — launches, satellites and orbits
  • Search — federated search and reports
  • Pass — passport account and SSO
  • Corpora — read-only corpus origins
  • e01 — self-hosted corpora and tools

Text and metadata only; each target carries its own sources. Missing data is published as no-data, never estimated.