1 回答
2
C 中的字符串是以null 结尾的。函数,例如printf()
or strlen()
,期望字符串末尾有一个空字节,这是一个值为 0 的字节。
当您在 C 中动态分配内存时,它是由操作系统分配的。调用时malloc()
(相对于calloc()
),您无法保证收到时内存的内容是什么。这就是您的代码具有未定义行为的原因 - 当系统返回的内存恰好0
是最后一个字节时,您的代码将运行良好。如果还有其他内容,printf()
将继续写入输出。
您应该考虑这种行为并将字符串的最后一个字节显式设置为0
:
int ciphertext_len = strlen(ciphertext);
// allocate ciphertext_len + 1 bytes for the plaintext output
for (int i = 0; i < ciphertext_len; i++) {
// your substitution logic
// plaintext[i] = ...
}
plaintext[ciphertext_len] = 0;
其他被认为是安全做法的替代方法总是将您收到的内存归零memset()
:
#include <string.h>
// store the size in bytes of the memory block you wish to allocate
int mem_block_size = (strlen(ciphertext) + 1) * sizeof(char);
// allocate the memory
char * plaintext = malloc(mem_block_size);
// set the memory to zeroes
memset(plaintext, 0, mem_block_size);
于 2020-06-14T10:04:00.650 回答