コードにはいくつかのメモリ不具合があります。おそらく、以下のより良い仕事になります。
#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 –
ここで、「出力」にスペースを割り当てましたか?あなたは現在の出力が何であるかを提示しましたが、期待される出力は何か言及できますか? [MCVE]の作成方法をご覧ください。 –
あなたの 'output'は十分大きな配列のために割り当てられる必要があります。 – chrisaycock