Technology1 min read

CodeSOD: Oh, K?

By · Published by Everything Blog

In short

The problematic implementation employed nested loops to iterate across districts and customers to format and produce output. Unable to determine why the original inner loop counter was continually overwritten, the initial author duplicated the counter variable and blamed a memory violation. Pierre discovered that a separate calculation assigning a string length directly within the loop body caused the value to overwrite itself. Cleaner code structure rather than variable duplication would have made the assignment bug immediately obvious.

Key points

  • Excessive complexity and code obfuscation can cause developers to misidentify standard as…: Excessive complexity and code obfuscation can cause developers to misidentify standard assignment bugs as memory violations.
  • Duplicating loop counters serves as an ineffective workaround that obscures the true unde…: Duplicating loop counters serves as an ineffective workaround that obscures the true underlying programming error.
  • Structuring loops cleanly improves visibility and helps engineers detect accidental varia…: Structuring loops cleanly improves visibility and helps engineers detect accidental variable reassignments within the same block.

Sources checked by our analysis pipeline: 1

Pierre found this cry for help:

for (j = 0; j < DISTRICT_CARDINALITY; j++) {

/*

* A poor way to work around some sort of memory

* violation. k gets clobbered, so I buffer l with it.

* Help?

*/

for (k = 0, l = 0; k < customers; k++, l++) {

/* c_id */

FPRINTF(output, "%d", l + 1);

METAPRINTF((output, "%c", delimiter));

Honestly, I'm always a little worried in C-like languages when the loop variable isn't scoped to the loop and declared in place. Always concerning, so when there's concerns with clobbering, I'm not surprised.

This iterates across a set of "districts", and then iterates across a list of customers. Standard output functions are replaced with macros, and honestly, I don't know that I want to know what happens in METAPRINTF

.

But fine, this iterates across a bunch of stuff and generates output. It's the comment that we're really curious about. "Some sort of memory violation", so we duplicate our loop variable. What on earth could be happening here?

Well, Pierre found the "memory violation", which…

Technology