코드에 메모리 버그가 있습니다. 아마도 다음이 더 잘 작동 것 :
#include <stdio.h>
#include <string.h>
#define min(i, j) ((i) < (j) ? (i) : (j))
int main(int argc, char const *argv[])
{
char *output;
int i;
/* Allocate a buffer large enough to hold the smallest of the two strings
* passed in, plus one byte for the trailing NUL required at the end of
* all strings.
*/
output = malloc(min(strlen(argv[1]), strlen(argv[2])) + 1);
/* Iterate through the strings, XORing bytes from each string together
* until the smallest string has been consumed. We can't go beyond the
* length of the smallest string without potentially causing a memory
* access error.
*/
for(i = 0; i < min(strlen(argv[1]), strlen(argv[2])) ; i++)
output[i] = argv[1][i]^argv[2][i];
/* Add a NUL character on the end of the generated string. This could
* equally well be written as
*
* output[min(strlen(argv[1]), strlen(argv[2]))] = 0;
*
* to demonstrate the intent of the code.
*/
output[i] = '\0';
/* Print the XORed string. Note that if characters in argv[1]
* and argv[2] with matching indexes are the same the resultant byte
* in the XORed result will be zero, which will terminate the string.
*/
printf("XOR: %s\n", output);
return 0;
}
을 지금까지 printf
이가는대로, x^x
= 0 그리고 \0
는 C.
행운을 빕니다
에서 문자열 종결 있음을 유의하십시오.
이 부분을 참조하십시오 https://stackoverflow.com/questions/39262323/print-a-string-variable-with-its-special-characters –
여기서'output'을위한 공간을 할당 했습니까? 현재 출력물이 무엇인지 알려 주었지만 예상되는 출력물을 언급 할 수 있습니까? [MCVE]를 만드는 방법을 참조하십시오. –
'출력'은 충분히 큰 배열에 할당해야합니다. – chrisaycock