Search code examples
cpointersmallocvalgrind

Why do I get an error on this program that uses malloc?


A program that ciphers a plaintext. key and value are passed into a function, and function returns a pointer. Not sure why compiler is screaming.

int main() {
  char *ciphertext = ciphering(key, plaintext);
  printf("ciphertext: %s\n", ciphertext);
  free(ciphertext);
}

char *ciphering(string key, string plaintext) {
  int n = strlen(plaintext);
  char *ciphertext = malloc(n + 1);

  // for loop fills in the cipher in ciphertext
  for (int i = 0; i < n; i++) {
    if (isupper(plaintext[i]))
      ciphertext[i] = toupper(key[(tolower(plaintext[i]) - 97)]);
    else if (islower(plaintext[i]))
      ciphertext[i] = tolower(key[(tolower(plaintext[i]) - 97)]);
    else
      ciphertext[i] = plaintext[i];
  }
  return ciphertext;
}
//==820==  Uninitialised value was created by a heap allocation

Solution

  • You forgot to null terminate the generated string.

    char *ciphertext = malloc(n + 1);
    ciphertext[n] = '\0';