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. ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.