Home > OS >  Bitwise XOR on unsigned char is terminating program without error
Bitwise XOR on unsigned char is terminating program without error

Time:05-22

I'm trying to create a 64 bit integer as class in C , I know this already exists in the C header stdint.h but I thought it could be a fun challenge.

Anyway, I am trying to perform a bitwise XOR operation on three unsigned chars, and the program keeps stopping without warning, it just pauses for a split second and then stops:

unsigned char* a = (unsigned char*) 1;
unsigned char* b = (unsigned char*) 2;
unsigned char* c = (unsigned char*) 3;

unsigned char* result = (unsigned char*) malloc(sizeof(unsigned char));

std::cout << "Trying" << std::endl;
*result = *a ^ *b ^ *c;
std::cout << "Done!" << std::endl;

The output being:

PS C:\Users\super\Desktop> ./test.exe
Trying
PS C:\Users\super\Desktop>

I am using Windows 10 if that helps, let me know if you need any other information, and thanks for any help you can give me :)

CodePudding user response:

You're trying to dereference invalid pointers. You want to get rid of a lot of those *s.

unsigned char a = 1;
unsigned char b = 2;
unsigned char c = 3;

unsigned char* result = (unsigned char*) malloc(sizeof(unsigned char));

std::cout << "Trying" << std::endl;
*result = a ^ b ^ c;
std::cout << "Done!" << std::endl;

Why are you allocating a single byte (sizeof(unsigned char) is 1 by definition) on the heap for the result? You could just make that another unsigned char variable, too.

Editorial note: you also don't need to use std::endl.

CodePudding user response:

Your code is crashing because you are dereferencing pointers a,b,c which are not pointing at valid memory addresses that can be read from.

Carl's answer shows you how to rewrite this code to not use pointers at all for a,b,c.

But, if for some reason, you actually did need to pass around integers type-casted as pointers (for instance, because you are passing them through a C API that requires this), then you need to type-cast the pointers back into integers, not dereference the pointers, eg:

unsigned char* a = reinterpret_cast<unsigned char*>(static_cast<std::uintptr_t>(1));
unsigned char* b = reinterpret_cast<unsigned char*>(static_cast<std::uintptr_t>(2));
unsigned char* c = reinterpret_cast<unsigned char*>(static_cast<std::uintptr_t>(3));

unsigned char* result = new unsigned char;

std::cout << "Trying" << std::endl;
*result = static_cast<unsigned char>(reinterpret_cast<std::uintptr_t>(a))
        ^ static_cast<unsigned char>(reinterpret_cast<std::uintptr_t>(b))
        ^ static_cast<unsigned char>(reinterpret_cast<std::uintptr_t>(c));
std::cout << "Done!" << std::endl;

...

delete result;
  • Related