Search code examples
cstringxorargv

XOR two strings from argv in C


Want to XOR two strings fetched from argv. I checked this question How to xor two string in C? but it could not solve it for me.

#include <stdio.h>
#include <string.h>

int main(int argc, char const *argv[]) {
  char output[]="";

  int i;
  for (i=0; i<strlen(argv[1]); i++){
      char temp = argv[1][i]^argv[2][i];
      output[i]=  temp;

  }
  output[i] = '\0';
  printf("XOR: %s\n",output);
  return 0;
}

When I use lldb to debug my output ("(lldb) print output") it is /a/x16/t/x13 but it can not be printed by printf(). I know that it is not a string anymore. Can you help me how to make it able to be printf:ed. The text that is printed in the terminal is "XOR: "


Solution

  • There's some memory bugs in your code. Perhaps the following would work better:

    #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;
      }
    

    As far as printf goes, keep in mind that x ^ x = 0 and that \0 is the string terminator in C.

    Best of luck.