-1

I have this little program that performs a xor operation over two char* but I can't tell if b1 is changed after the function call. When I try to do a std::cout the program does not print anything.

#include <iostream>
#include <malloc.h>
#include <cstring>

void xorBlocks(char *b1, char *b2) {
  for (int i = 0; i <5; i++) {
    b1[i] ^= b2[i];
 }
  std::cout <<b1; 
}

int main()
{   
char* buffer = (char *) malloc(10);
char* previousBlock = (char *) malloc(10);
const char *iv = (const char *)"00111";
//printf(iv);
memcpy(previousBlock, iv, 5);
//printf(previousBlock);
memcpy(buffer, iv, 5);
//printf(buffer);
xorBlocks((char *) buffer, (char *) previousBlock);
return 0;
}
Alex544
  • 25
  • 4
  • 1
    All of those `(char *)` and `(const char *)` disable type safety. The only ones needed are the ones next to `malloc` but `malloc` shouldn't be used here. `char buffer[10];` is far better, and even then `std::array buffer;` is worth considering. – François Andrieux Dec 30 '19 at 14:30
  • 2
    The first byte of each of `b1` and `b2` is '0' (decimal 48). '0' xor '0' evaluates to 0. Hence the first byte of b1 becomes 0, which means `b1` is an empty string and nothing is printed. – jarmod Dec 30 '19 at 14:30
  • 1
    `x ^ x` is zero for all integers `x`. – molbdnilo Dec 30 '19 at 15:16

2 Answers2

2

This function

void xorBlocks(char *b1, char *b2) {
  for (int i = 0; i <5; i++) {
    b1[i] ^= b2[i];
 }
  std::cout <<b1; 
}

does not perform the XOR operation applied to the pointers b1 and b2. It performs the XOR operation applied to characters pointed to by these pointers. So the pointers themselves are not changed. It is the characters pointed to by the pointer b1 are changed.

Moreover as the pointer as the first character pointed to by the pointer b1 will became equal to 0 then nothing will be outputted in this statement

  std::cout <<b1; 

has undefined behavior.

Pay attention to that these castings

const char *iv = (const char *)"00111";

and

xorBlocks((char *) buffer, (char *) previousBlock);

are redundant. You may just write

const char *iv = "00111";

and

xorBlocks( buffer, previousBlock);

And the function should be declared like

void xorBlocks(char *b1, const char *b2);

because characters pointed to by the pointer b2 are not changed in the function.

And in C++ you should use the operator new instead of the function malloc.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

You are trying to use xor with two same values.

const char *iv = (const char *)"00111";
memcpy(previousBlock, iv, 5);
memcpy(buffer, iv, 5);

If two bits are the same (both are 0 or both are 1), then xor returns 0.

As a result, you have the line (buffer) =\0\0\0\0\0

If you can’t understand what is inside the string, just print codes of all characters.

for (char c : buffer)
    std::cout << int(c) << ' ';