cChar-array正在打印额外的垃圾内存

  • 本文关键字:内存 打印 cChar-array
  • 更新时间 :
  • 英文 :


这个程序应该输出VYGHBUTMDE,但它在末尾添加了一些垃圾字符。为什么会这样?

#include <stdio.h>
#include <string.h>
int
encrpypt(char ciphertext_buffer[], char plaintext[], char key[]) {
  int i;
  for (i=0; i<strlen(plaintext); i++) {
    ciphertext_buffer[i] = (char) ( ( ((int)plaintext[i] - 65 + (int)key[i%(strlen(key))] - 65) % 26 ) + 65 );
  }
  return 0;
}
int
main() {
  char ciphertext_buffer[10];
  encrpypt(ciphertext_buffer, "THISISCOOL", "CRYPT");
  printf("%sn", ciphertext_buffer);
  return 0;
}

由于您只为10字节的字符串分配了一个10字节的数组,因此终止的null字符"无处可去"。请考虑将缓冲区大小增加到至少一个大于字符串长度(以"可见"字符为单位)的字符。

终止字符串不是null。这是一个略有修改的版本:(尽管仍然存在问题)

#include <stdio.h>
#include <string.h>
int
encrpypt(char ciphertext_buffer[], char plaintext[], char key[]) {
  int i;
  for (i=0; i<strlen(plaintext); i++) {
    ciphertext_buffer[i] = (char) ( ( ((int)plaintext[i] - 65 + (int)key[i%(strlen(key))] - 65) % 26 ) + 65 );
  }
  ciphertext_buffer[i] = 0;
  return 0;
}
int
main() {
  char ciphertext_buffer[11];
  encrpypt(ciphertext_buffer, "THISISCOOL", "CRYPT");
  printf("%sn", ciphertext_buffer);
  return 0;
}

一个更大的问题是,您没有进行任何边界检查。这里有一个更好的版本:

#include <stdio.h>
#include <string.h>
int
encrpypt(char ciphertext_buffer[], char plaintext[], char key[], int size) {
  int i;
  for (i=0; i<strlen(plaintext); i++) {
    if (i > size - 1) break;
    ciphertext_buffer[i] = (char) ( ( ((int)plaintext[i] - 65 + (int)key[i%(strlen(key))] - 65) % 26 ) + 65 );
  }
  ciphertext_buffer[i] = 0;
  return 0;
}
int
main() {
  char ciphertext_buffer[11];
  encrpypt(ciphertext_buffer, "THISISCOOL", "CRYPT", sizeof(ciphertext_buffer));
  printf("%sn", ciphertext_buffer);
  return 0;
}

Char数组必须以'/0'终止。因此,u总是需要将char数组分配为最大字符串大小+1。

请尝试以下更正。

#include <stdio.h>
#include <string.h>
int encrpypt(char ciphertext_buffer[], char plaintext[], char key[]) {
  int i;
  for (i=0; i<strlen(plaintext); i++) {
    ciphertext_buffer[i] = (char) ( ( ((int)plaintext[i] - 65 + (int)key[i%(strlen(key))] - 65) % 26 ) + 65 );
  }
 ciphertext_buffer[i] = '';
  return 0;
}
int
main() {
  char ciphertext_buffer[11];
  encrpypt(ciphertext_buffer, "THISISCOOL", "CRYPT");
  printf("%sn", ciphertext_buffer);
  return 0;
}

最新更新