Reputation: 121
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
Upvotes: 0
Views: 59
Reputation: 81926
You forgot to null terminate the generated string.
char *ciphertext = malloc(n + 1);
ciphertext[n] = '\0';
Upvotes: 4