O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Defect Smashing

We have a reproducible scenario that demonstrates the presence of a memory management bug in our C code. Now that we have a failing test, we need to figure out what is actually wrong with our code. Let’s take another look.

 caesar.c
 char *caesar(int shift, char *input)
 {
  char *output = malloc(strlen(input));
  memset(output, '\0', strlen(input));
 
  for (int x = 0; x < strlen(input); x++) {
  if (isalpha(input[x])) {
  int c = toupper(input[x]);
  c = (((c - 65) + shift) % 26) + 65;
  output[x] = c;
  } else {
  output[x] = input[x];
  }
  }
 
  return output;
 }

A closer examination reveals the issue. As with most programming problems, there are a few different ways to address this. We will again take the easy way out. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required