为什么我在这个使用 malloc 的程序上会出错?
Why do I get an error on this program that uses malloc?
一个加密明文的程序。 key 和 value 被传递给一个函数,function returns 一个指针。不确定为什么编译器会尖叫。
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
您忘记以 null 终止生成的字符串。
char *ciphertext = malloc(n + 1);
ciphertext[n] = '[=10=]';
一个加密明文的程序。 key 和 value 被传递给一个函数,function returns 一个指针。不确定为什么编译器会尖叫。
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
您忘记以 null 终止生成的字符串。
char *ciphertext = malloc(n + 1);
ciphertext[n] = '[=10=]';